-1

I have these two types:

type FooId = string
type BarId = string

I use it wherever I want to inform about what type of string I expect there.

Due to the nature of TS I can still do something like this:

const foo1: FooId = "bar" 
const foo1: FooId = "bar" as FooId
const foo2: FooId = "bar" as BarId;

Is it possible forbid the third assignment, only, somehow? (or even to forbid also the first, but still allow the second)

I want to avoid that BarId values can be used as FooId values (and vice versa).

Sebastian Barth
  • 4,079
  • 7
  • 40
  • 59

1 Answers1

-1

Not in this way.

type is like an alias, you are creating two alias to string.

If you know that FooId could only be some string, maybe foo and bar, you should use unions with literals

type FooId = "bar" | "foo"

For more specific use, try template strings

Nullndr
  • 1,624
  • 1
  • 6
  • 24