我正在尝试创建一种类型,其中一个字符串是一个对象,但每个其他字符串键都等于一个字符串。这是我尝试过的所有代码。
interface SubElement {
someProperty: string;
}
Run Code Online (Sandbox Code Playgroud)
'subElement'这是我想要在主对象的属性中使用的对象类型。
interface MainType1 {
[key: string]: string;
/* Error: Property 'subElement' of type 'SubElement' is not assignable to 'string' index type 'string'.ts(2411) */
subElement: SubElement;
}
Run Code Online (Sandbox Code Playgroud)
这个错误出现在接口声明中,并且它也作为类型而不是接口出现错误。
type MainType3 = {
/* Error: Property 'subElement' of type 'SubElement' is not assignable to 'string' index type 'string'.ts(2411) */
subElement: SubElement;
[key: Exclude<string, 'subElement'>]: string;
}
Run Code Online (Sandbox Code Playgroud)
这与第一个有相同的错误。
/* Type doesn't error */
type MainType2 = {
subElement: SubElement;
} & {
[key: string]: string; …Run Code Online (Sandbox Code Playgroud)