gpt4 book ai didi

typescript - 具有动态和静态属性的接口(interface)

转载 作者:行者123 更新时间:2023-12-02 02:56:42 25 4
gpt4 key购买 nike

我有一个关于更动态的接口(interface)类型的问题,其中动态和静态属性可以一起使用——即使它们属于不同类型。这可能吗?如果是,它有任何意义吗?

假设我想要这样的东西。

type MyCustomType = {
foo: string;
};

export interface MyInterface {
[key: string]: MyCustomType;
bar: string;
};

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

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

Property 'bar' of type 'string' is not assignable to string index type MyCustomType.

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

export interface MyInterface {
[key: string]: MyCustomType | string;
bar: string;
};

非常感谢任何建议:)

最佳答案

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

type MyCustomType = {
foo: string;
};

type MyInterface = {
[key: string]: MyCustomType;
} & { bar: string };

为了让交集起作用,MyInterface 必须是一个类型。

关于typescript - 具有动态和静态属性的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60954483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com