Jos*_*ter 5 typescript typescript-typings
我正在尝试创建一种类型,其中一个字符串是一个对象,但每个其他字符串键都等于一个字符串。这是我尝试过的所有代码。
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;
}
/* Error: Type '{ subElement: { someProperty: string; }; }' is not assignable to type 'MainType2'.
Type '{ subElement: { someProperty: string; }; }' is not assignable to type '{ [key: string]: string; }'.
Property 'subElement' is incompatible with index signature.
Type '{ someProperty: string; }' is not assignable to type 'string'.ts(2322) */
let someVar: MainType2 = {
subElement: {
someProperty: ''
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试初始化该类型的任何内容时,会出现此错误,因为它期望'subElement'是一个字符串。
/* Type doesn't error */
type MainType4 = {
subElement: SubElement;
} & {
[key: Exclude<string, 'subElement'>]: string;
}
/* Error: Type '{ subElement: { someProperty: string; }; }' is not assignable to type 'MainType2'.
Type '{ subElement: { someProperty: string; }; }' is not assignable to type '{ [key: string]: string; }'.
Property 'subElement' is incompatible with index signature.
Type '{ someProperty: string; }' is not assignable to type 'string'.ts(2322) */
let otherVar: MainType4 = {
subElement: {
someProperty: ''
}
}
Run Code Online (Sandbox Code Playgroud)
与之前相同的错误,'subElement'预计是一个字符串。
这是可能的还是我需要类似的东西{[key: string]: string | SubElement}?
| 归档时间: |
|
| 查看次数: |
1156 次 |
| 最近记录: |