0

I wan't to distinguish type aliases in such a way:

type EntityID = number;
type AnotherEntityID = number;

let entityID: EntityID = 1;
let anotherEntityID: AnotherEntityID = 2;

entityID = anotherEntityID

I expect that the last line must raise type check error

Bergutov Ruslan
  • 157
  • 2
  • 14
  • 1
    I don't have an answer for you, as I'm not sure the *exact* way it should be implemented, however I can point you towards what you need. Look into "opaque types". It's the name of what you want to have here - you can make something that's essentially a number but it's distinguishable from a different type. E.g., `person.id = person.age` can thrown a type error, since they are different, even if each is a number itself. IIRC, in TS this is achievable through what's called (in TS) "branded types". – VLAZ Nov 23 '19 at 15:45
  • Both `EntityID` and `AnotherEntityID` are just aliases of `number`. `entityID` and `anotherEntityID` have the same type, i.e. `number`. This is why they can be assigned one to another without any error or warning. TypeScript doesn't care about the names you give to your types. All it cares is the structure of your types. Two types that have the same structure are compatible, no matter if they are related or not. – axiac Nov 23 '19 at 15:50
  • thanks to @VLAZ, this is what i need, you can repost your comment as full answer and i mark it as answer – Bergutov Ruslan Nov 23 '19 at 15:56
  • Possible duplicate of [How to define an opaque type in TypeScript?](https://stackoverflow.com/questions/56737033/how-to-define-an-opaque-type-in-typescript) – Etheryte Nov 23 '19 at 16:00

0 Answers0