具有动态和静态属性的接口

ent*_*ull 2 typescript

我有一个关于更动态的接口的问题,其中动态和静态属性可以一起使用 - 即使它们是不同的类型。这可能吗?如果是的话,这还有什么意义吗?

假设我想要这样的东西。

type MyCustomType = {
    foo: string;
};

export interface MyInterface {
    [key: string]: MyCustomType;
    bar: string;
};
Run Code Online (Sandbox Code Playgroud)

我想确保某个 prop (我事先不知道其名称)指向 type 的值MyCustomType。我确实知道其中的其余属性MyInterface的名称,并且它们指向其他类型。

上面的代码会导致以下错误:

Property 'bar' of type 'string' is not assignable to string index type MyCustomType.
Run Code Online (Sandbox Code Playgroud)

我可以通过使用交集(如下例所示)来解决这个问题,或者any 但是..这也会影响我的动态道具并破坏其类型的保证。

export interface MyInterface {
    [key: string]: MyCustomType | string;
    bar: string;
};
Run Code Online (Sandbox Code Playgroud)

非常感谢任何建议:)

Ali*_*deh 5

这可以通过以下方式使用交集来完成:

type MyCustomType = {
    foo: string;
};

type MyInterface = {
    [key: string]: MyCustomType;
} & { bar: string };
Run Code Online (Sandbox Code Playgroud)

为了使交叉点起作用,MyInterface 必须是一种类型。