简体   繁体   English

获取接口 object 的属性

[英]Get property of interface object

In a Typescript project I'm working on I have the following interfaces:在我正在处理的 Typescript 项目中,我有以下接口:

interface Credentials {
    google?: string,
    facebook?: string,
}

export interface Configuration {
    credentials: Credentials;
}

In a different class I am trying to get the value of one of the properties of Credentials based on the given string:在不同的 class 中,我试图根据给定的字符串获取 Credentials 的属性之一的值:

export default class Authorize {

    _config : Configuration;

    constructor(config?: Configuration) {
        this._config = config;
    }

    authorize(provider : string) {
        const test = getProperty(this._config.credentials, provider);
        console.log(test);
    }
}

Where the getProperty is: getProperty 在哪里:

export function getProperty<T, K extends keyof T>(obj: T, key: K) {
    console.log(typeof key);
    return obj[key];
}

Unfortunately this is not possible since getProperty gives an error:不幸的是,这是不可能的,因为 getProperty 给出了错误:

TS2345: Argument of type 'string' is not assignable to parameter of type 'keyof Credentials'. TS2345:'string' 类型的参数不可分配给'keyof Credentials' 类型的参数。

Is there a different way to get the property of the Credentials object by string?是否有其他方法可以通过字符串获取凭据 object 的属性?

I fixed it by adding [key: string]: any, to the Credentials interface.我通过将[key: string]: any,添加到 Credentials 接口来修复它。

So the final interface looks like:所以最终的界面是这样的:

interface Credentials {
    [key: string] : any,
    google?: string,
    facebook?: string,
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM