'How to restrict type assignment to type only ignoring the type it consists of [duplicate]

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).



Solution 1:[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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nullable