1
我有以下interface
。Typescript索引签名的不同类型
interface IDetails {
name: string;
age: number;
}
interface IConfig {
appName: string;
userDetails: IDetails;
[key: string]: string | IDetails
}
const details: IConfig = {
appName: 'test',
userDetails: {
name: 'xyz',
age: 67,
},
}
const t: string = 'userDetails'
const name: string = details[t].name
// ^^^^
// throws the following error
//
// Property 'name' does not exist on type 'string | IDetails'.
// Property 'name' does not exist on type 'string'.
当我尝试将多个类型/接口分配给密钥签名时,出现此错误。我知道我可以使用[key: string]: any
。但是,我不想概括它。有没有任何可能的方法来完成这项工作?
你可以转换为一个IDetails:'( details [t])。name' –
感谢您的提示。为什么'string | IDetails'不工作? –
为什么你有'[key:string]:string | IDetails'?没有它,你想要的只是工作。你是否期待更多物业? –