如何定义一个在对象内包含可选数据的 TypeScript 接口(interface)?
我的意思是:
export interface IMyInterface
{
name: string;
data:
{
size: number;
color?: string;
[any: string]?: any; // Error on this line!!!
};
};
我知道您可以使用“?”定义可选数据像这样签名:
color?: string;
但是如何在对象内定义附加可选数据
let myObj: IMyInterface =
{
name: "theName",
data:
{
size: 10,
color: "red",
moreOptionalData: { x: 'y' } // This line will throw an error (incampatable interface)
}
};
最佳答案
感谢 CRice 的评论和 OJ-Kwon 的洞察力,解决方案非常简单,我只需删除“?”标志。
export interface IMyInterface
{
name: string;
data:
{
size: number;
color?: string;
[any: string]: any; // optional additional data (no need for '?')
};
};
let myObj: IMyInterface =
{
name: "theName",
data:
{
size: 10,
color: "red",
moreOptionalData: { x: 'y' } // Now it's OK
}
};
关于typescript - 如何在 TypeScript 接口(interface)对象中定义可选数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48272172/