Typescript索引签名的不同类型

时间:2016-12-17 12:58:39

标签: javascript typescript

我有以下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。但是,我不想概括它。有没有办法使这项工作?

Link to TypeScript Playground

1 个答案:

答案 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
}