小编Nim*_*mai的帖子

使用TypeScript中的基本类型创建唯一类型?

我想给类对象提供唯一的id类型,即使它们都是字符串.我尝试使用type,我尝试从具有唯一子类名称的基类派生.

请参阅以下示例.既不typeextends不允许我指示编译器将它们视为唯一类型.我仍然可以将HumanId传递给期望AnimalId的函数,反之亦然.

我认为它们是对象兼容的,从底层的JavaScript角度来看,这是完全有道理的.事实上,如果我向AnimalId添加一个唯一的成员,我会得到我期望的错误:

Argument of type 'HumanId' is not assignable to parameter of type 'AnimalId'.

使用TypeScript有一个很好的方法来为基本类型创建唯一类型别名吗?

// 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 = …
Run Code Online (Sandbox Code Playgroud)

typescript

6
推荐指数
2
解决办法
1040
查看次数

标签 统计

typescript ×1