在 TypeScript 中创建联合函数类型
Create a union function types in TypeScript
我正在尝试为箭头函数创建联合类型。
type ItemType = {
createTime: number;
totalTime: number;
text: string;
};
type ObjType = {
callback: ((item: string) => void) | ((item: ItemType) => void);
}
let obj: ObjType = {
callback: (item: string) => {
console.log(item)
}
}
到目前为止效果很好。
然后我要调用函数。
obj.callback('text');
显示错误
Argument of type 'string' is not assignable to parameter of type 'string & ItemType'.
Type 'string' is not assignable to type 'ItemType'.
callback
的类型变成了(item: string & ItemType) => void
。
我做错了什么?
如果 ObjType
有两种可能性,实现它的对象必须实现这两种可能性才能成为有效的 ObjType
。如果 obj
将只有一个版本的回调而不是另一个版本,我认为您需要使 ObjType
通用并接受一个类型参数说明它将是哪个版本,如下所示:
type ItemType = {
createTime: number;
totalTime: number;
};
type ObjType<Item extends string | ItemType> = {
callback: (item: Item) => void;
};
let obj1: ObjType<ItemType> = {
callback: (item) => {
console.log(item);
},
};
obj1.callback({createTime: 0, totalTime: 0});
let obj2: ObjType<string> = {
callback: (item) => {
console.log(item);
},
};
obj2.callback("example");
我正在尝试为箭头函数创建联合类型。
type ItemType = {
createTime: number;
totalTime: number;
text: string;
};
type ObjType = {
callback: ((item: string) => void) | ((item: ItemType) => void);
}
let obj: ObjType = {
callback: (item: string) => {
console.log(item)
}
}
到目前为止效果很好。
然后我要调用函数。
obj.callback('text');
显示错误
Argument of type 'string' is not assignable to parameter of type 'string & ItemType'.
Type 'string' is not assignable to type 'ItemType'.
callback
的类型变成了(item: string & ItemType) => void
。
我做错了什么?
如果 ObjType
有两种可能性,实现它的对象必须实现这两种可能性才能成为有效的 ObjType
。如果 obj
将只有一个版本的回调而不是另一个版本,我认为您需要使 ObjType
通用并接受一个类型参数说明它将是哪个版本,如下所示:
type ItemType = {
createTime: number;
totalTime: number;
};
type ObjType<Item extends string | ItemType> = {
callback: (item: Item) => void;
};
let obj1: ObjType<ItemType> = {
callback: (item) => {
console.log(item);
},
};
obj1.callback({createTime: 0, totalTime: 0});
let obj2: ObjType<string> = {
callback: (item) => {
console.log(item);
},
};
obj2.callback("example");