我有以下interface
。
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
。但是,我不想概括它。有没有办法使这项工作?
答案 0 :(得分:4)
如果您要动态访问details
的属性,那么最好使用type guards:
function isDetails(obj: string | IDetails): obj is IDetails {
return Object.keys(obj).length === 2 && typeof obj["name"] === "string" && typeof obj["age"] === "number";
}
然后你可以这样做:
if (isDetails(details[t])) {
// details[t].name should be fine with the compiler
}