打字稿:创建一个从原始类型扩展的类型?
Typescript : create a type extending from primitive type?
在我的 angular 项目中,我想创建一个从字符串扩展的自定义类型。我的情况是我想创建一个 "ID" 类型来将字符串与 idstring 分开。
let str = String("tutu");
let id = ID("ec1s69azs");
this.service.getUserById(str) => doesn't compile;
this.service.getUserById(id) => compile;
以后我可能想在"ID"类型中添加id验证器
我想知道是否可行,因为我已经尝试了很多 "hacks" 但 none 给我想要的结果。
class ObjectID extends String {
}
export type ID = ObjectID;
或
interface StringConstructor {
new(value?: any): String;
(value?: any): string;
readonly prototype: String;
fromCharCode(...codes: number[]): string;
}
export type ID = StringConstructor;
不要认为您需要扩展 string
,您可以使用标记类型来实现所需的结果。
type ObjectID = string & { __type: 'Id'}
function ID(n: string): ObjectID{
return n as any;
}
// Usage
function getUserById(id: ObjectID) {
}
getUserById(ID("1")); //ok
getUserById("1"); // error
您需要定义一个辅助函数来创建该类型的实例或使用强制转换,但如果您传递一个简单的字符串,调用站点会报错。
这个article has a bit more of a discussion on the topic. Also the typescript compiler uses this approach for paths
在我的 angular 项目中,我想创建一个从字符串扩展的自定义类型。我的情况是我想创建一个 "ID" 类型来将字符串与 idstring 分开。
let str = String("tutu");
let id = ID("ec1s69azs");
this.service.getUserById(str) => doesn't compile;
this.service.getUserById(id) => compile;
以后我可能想在"ID"类型中添加id验证器
我想知道是否可行,因为我已经尝试了很多 "hacks" 但 none 给我想要的结果。
class ObjectID extends String {
}
export type ID = ObjectID;
或
interface StringConstructor {
new(value?: any): String;
(value?: any): string;
readonly prototype: String;
fromCharCode(...codes: number[]): string;
}
export type ID = StringConstructor;
不要认为您需要扩展 string
,您可以使用标记类型来实现所需的结果。
type ObjectID = string & { __type: 'Id'}
function ID(n: string): ObjectID{
return n as any;
}
// Usage
function getUserById(id: ObjectID) {
}
getUserById(ID("1")); //ok
getUserById("1"); // error
您需要定义一个辅助函数来创建该类型的实例或使用强制转换,但如果您传递一个简单的字符串,调用站点会报错。
这个article has a bit more of a discussion on the topic. Also the typescript compiler uses this approach for paths