2016-12-17 50 views
1

我有以下interfaceTypescript索引签名的不同类型

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

+0

你可以转换为一个IDetails:'( details [t])。name' –

+0

感谢您的提示。为什么'string | IDetails'不工作? –

+0

为什么你有'[key:string]:string | IDetails'?没有它,你想要的只是工作。你是否期待更多物业? –

回答

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 
} 
相关问题