Ale*_*rff 6 types type-conversion webstorm typescript typescript2.0
我想描述一些带有嵌套对象的接口。不为嵌套对象创建接口怎么办?
interface ISome {
strProp:string;
complexProp:{
someStrKeyWhichIsDynamic:{
value:string;
optValue?:string;
}
};
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过(UPD:实际上还可以)
interface ISome {
strProp:string;
complexProp:{
[someStrKeyWhichIsDynamic:string]:{
value:string;
optValue?:string;
}
};
}
Run Code Online (Sandbox Code Playgroud)
但是我不能分配一个像
let dynamicStrKey = 'myKey';
{
strProp:'str',
complexProp:{
[dynamicStrKey]:{
value:'something here',
optValue: 'ok, that too',
}
};
Run Code Online (Sandbox Code Playgroud)
转换为ISome没有类型断言的类型的变量<ISome>。至少WebStorm将此任务突出显示为错误。
如何正确描述嵌套对象?
Ale*_*rff 14
最后,我认为我的第二个变体是正确的
interface ISome {
strProp:string;
complexProp:{
[someStrKeyWhichIsDynamic:string]:{
value:string;
optValue?:string;
}
};
}
Run Code Online (Sandbox Code Playgroud)
对于动态键,您可以只写[dynamic:string]来指定这里将是一些字符串属性。似乎我遇到了与问题无关的 webstorm 错误。
顺便说一句,如果你有一些基于字符串枚举,您可能要使用[key in MyEnum]: {...}替代[key:string]。这解决了错误:
TS1337 索引签名参数类型不能是联合类型。
如果你有一个文字对象,例如
const obj = { prop1: 'blah', prop2: 'blahblah' }
您可能想要使用[key in keyof typeof obj]: {...}来描述您的动态键只能是 'prop1' 或 'prop2' (或者,更通用的值来自Object.keys(obj))
| 归档时间: |
|
| 查看次数: |
16804 次 |
| 最近记录: |