4
我想给类对象提供唯一的id类型,即使它们都是字符串。我尝试使用type
,我尝试从具有唯一子类名称的基类派生。在TypeScript中创建基本类型的唯一类型?
请看下面的例子。 type
和extends
都不允许我指示编译器将它们视为唯一类型。我仍然可以将HumanId传递给期望AnimalId的函数,反之亦然。
我知道它们是对象兼容的,而且从底层的JavaScript角度来看,这是非常重要的。事实上,如果我的唯一成员添加到AnimalId,我得到的错误我想到:
Argument of type 'HumanId' is not assignable to parameter of type 'AnimalId'.
是否与打字稿一个很好的方法,使独特类型的别名基本类型?
// type HumanId = string;
// type AnimalId = string;
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);
是啊。感谢您确认我不缺少语言功能。我认为能够声明'type HumanId = unique string'会很好。利用编译时检查基本类型以用于特定目的的一些方法。 – Nimai
为了什么是值得的,我使用了最简单的单行语法,并且做到了:'class HumanId extends BaseId {humanId}' – Nimai
如果你想要的只是类型检查,也许你可以引入HumanId和AnimalId作为类型.d.ts声明文件? – Kokodoko