我正在尝试创建一个类型来描述一个ES6代理对象,我将知道几个键的类型,其余的键将是通用的,回调作为一个值,我不知道它们的名字,直到运行时。
但是,如果我尝试这样的事情:
interface MyCallback {
(): void;
}
interface MyType {
myKey1: number;
[key: string]: MyCallBack;
}
我得到的错误如下:
[ts] Property 'myKey1' of type 'number' is not assignable to string index type 'MyCallback'.
如果我添加[key: string]: number
,我得到错误Duplicate string index signature
。
如果我重载它所以它就像number | MyCallback
,如果我尝试在MyType
实例上调用回调,我会收到此错误:
[ts] Cannot invoke an expression whose type lacks a call signature. Type 'number | MyCallback' has no compatible call signatures.
是否有可能有类似我试图在TypeScript中创建的类型?
答案是那样的。您可以使用交集类型完成此操作:
interface MyType {
myKey1: number;
}
interface MyCallBack {
(): void;
}
interface GenericCallbackType {
[key: string]: MyCallBack;
}
type CombinedType = MyType & GenericCallbackType;
const obj: CombinedType = {
myKey1: 8,
anyString: () => {}
}
如评论中所述,接受的答案不适用于分配,导致Property 'myKey1' is incompatible with index signature
错误。要处理作业我们可以利用@jcalz的答案here:
interface MyCallback {
(): void
}
interface MyType {
myKey1: number
}
const asCombinedType = <C>(
res: C & MyType & Record<Exclude<keyof C, keyof MyType>, MyCallback>
): C => res
const obj = asCombinedType({
anyKey: () => { /* ...*/ },
myKey1: 12
})
不可否认有点令人费解,但它完成了工作。