在TypeScript中,如何键入对象文字的特定键

时间:2017-01-09 17:28:34

标签: typescript

所以我有这个数据结构

export interface StoreData {
    msdb: {[tableName: string]: List<StoreModel>};
}

但我想只允许(并获取IntelliSence)我的tableName的特定字符串值。 所以我尝试了类似下面的内容,但它没有工作:

var tableNames:'table_campaigns' | 'table_resources'
export interface StoreData {
    msdb: {[tableName]: List<StoreModel>};
}

也尝试没有运气

interface IMyTables {
    'table_campaigns: string
    'table_resources: string;
}

type MyTables = keyof IMyTables;

export interface StoreData {
    participants: { [key: number]: any };
    threads: { [key: number]: any };
    messages: { [key: number]: any };
    msdb: {MyTables: List<StoreModel>};
}

也尝试了

type allMyTables = 'table_campaigns' | 'table_resources'

export interface StoreData {
    msdb: {[tableName: allMyTables]: List<StoreModel>};
}




Thanks for reading,

Sean

1 个答案:

答案 0 :(得分:2)

谢谢杰夫,做到了:

export interface StoreData {
    participants: { [key: number]: any };
    threads: { [key: number]: any };
    messages: { [key: number]: any };
    msdb: {
        'table_campaigns': List<StoreModel>;
        'table_resources': List<StoreModel>;
    };
}