I want to provide unique types of class objects, even if they are all strings. I tried to use type, and I tried to get a base class with unique subclass names.
See the following example. Neither typenor extendsdoes it allow me to instruct the compiler to treat them as unique types. I can still pass HumanId to a function waiting for AnimalId and vice versa.
I understand that they are compatible with objects, and this is because of the basic perspective of JavaScript, which makes the general sense. In fact, if I add a unique member to AnimalId, I will get the expected error:
Argument of type 'HumanId' is not assignable to parameter of type 'AnimalId'.
Is there a good approach with TypeScript to create unique type aliases for base types?
class id {
constructor(public value: string) { }
toString(): string { return this.value;}
}
class HumanId extends id { };
class AnimalId extends id { };
function humanTest(id: HumanId): void {
}
function animalTest(id: AnimalId): void {
}
let h: HumanId = new HumanId("1");
let a: AnimalId = new AnimalId("2");
animalTest(h);