是否可以在 TypeScript 类型和通用键类型中混合使用特定类型的键?

emp*_*cal 5 typescript typescript2.0

我正在尝试创建一个类型来描述一个 ES6 代理对象,其中我将知道几个键的类型,其余的键将是通用的,带有一个回调作为值,直到运行时我才知道它们的名称.

但是,如果我尝试这样的事情:

interface MyCallback {
  (): void;
}

interface MyType {
    myKey1: number;
    [key: string]: MyCallBack;
}
Run Code Online (Sandbox Code Playgroud)

我收到如下错误:

[ts] Property 'myKey1' of type 'number' is not assignable to string index type 'MyCallback'.
Run Code Online (Sandbox Code Playgroud)

如果我添加[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.
Run Code Online (Sandbox Code Playgroud)

是否有可能像我在 TypeScript 中尝试创建的类型一样?

bry*_*n60 1

答案是有点。您可以使用交叉类型来完成此操作:

interface MyType {
    myKey1: number;
}

interface MyCallBack {
    (): void;
}

interface GenericCallbackType {
    [key: string]: MyCallBack;
}

type CombinedType = MyType & GenericCallbackType;

const obj: CombinedType = {
    myKey1: 8,
    anyString: () => {}
}
Run Code Online (Sandbox Code Playgroud)