打字稿:使用带有字典的接口定义对象的初始状态

时间:2018-06-20 15:21:03

标签: typescript dictionary syntax interface initialization

我的界面定义如下:

export interface FullCache {
    // keys names are dynamic
    [cacheId: string]?: SingleCache;
}

export interface SingleCache {
    data: string;
}

所以一个FullCache对象示例可能看起来像这样:

{
    ca001:{data:'foo'},
    ca002:{data:'bar'}
}

但是,我无法弄清楚如何为FullCache定义初始状态,因为它使用密钥字典。我尝试简单地定义一个空对象:

export const fullCacheInitialState: FullCache = {

};

但是webpack给出错误error TS1131: Property or signature expected.

1 个答案:

答案 0 :(得分:3)

没有optional index signature这样的东西。以下问号是错误:

export interface FullCache {
    [cacheId: string]?: SingleCache; // error
}

索引签名已经像可选属性一样工作,因为不需要键。因此,您可以将其更改为

export interface FullCache {
    [cacheId: string]: SingleCache; // okay
}

或者,如果您尝试在访问缺少的属性时捕获FullCache对象might return undefined的事实,则可以这样定义它:

export interface FullCache {
    [cacheId: string]: SingleCache | undefined; // okay
}

任何一种方法都可以清除您的错误。希望能有所帮助。祝你好运!