首页 > 解决方案 > Typescript - 同一界面中相同类型的固定属性和可选属性

问题描述

正如标题所说,有一个接口,其中包括一个固定属性和可选属性,两者都是 type string

export interface Test{
    [index: string]: {
        'list': string[];    // <<< throws TS2411 error
        [index: string]: number;
    }
}

这会引发 TS 错误TS2411: Property 'list' of type 'string[]' is not assignable to string index type 'number'.

我该如何解决这个问题?

我知道list元素将存在于每个根索引对象中,所有其他属性(如果存在)都是数字类型。

如果我将界面更改为:

export interface Test{
    [index: string]: {
        'list': string[];    
        [index: string]?: number;  // <<< throws TS7008 error
    }
}

然后我得到TS7008: Member 'number' implicitly has an 'any' type.

标签: typescript

解决方案


这是因为您正在设置[index: string]: number;部分 - 允许您将任何字符串设置为数字,这也涵盖了“列表”的字符串,因此存在冲突。如果您需要“列表”值以及未知数量的其他值,我建议您这样做:

export interface Test {
  [index: string]: {
    list: string[];
    items: {
      [index: string]: number;
    }
  }
}

推荐阅读