arrays - 属性在类型上不存在/不能用作索引类型

标签 arrays typescript

我想要一个可以在其根中包含字符串的对象,并在 arrayValues 对象中包含一个字符串数组。这是将在应用中使用的配置对象。

此对象及其键将是动态的(通过用户状态值定义),因此我无法根据特定键名指定类型。

我将从我的应用程序的一部分向“arrayValues”添加数组,并从应用程序的另一部分向“过滤器”添加字符串。

但是我在访问对象属性时遇到错误:
TS PLAYGROUND

export type FiltersStateType = {
  filters:
    | {
        arrayValues: { // note: this should only appear once in filters object
          [key: string]: Array<string>
        }
      }
    | { [key: string]: string }
}

const example: FiltersStateType = {
  filters: {
    arrayValues: {
      sandwiches: ['ham', 'cheese'],
      milkshakes: ['choc', 'banana'],
    },
    randomString: 'hello',
  },
}

example.filters.arrayValues.sandwiches.filter((item: string) => item !== 'ham') 
// ❌ Property 'sandwiches' does not exist on type 'string | { [key: string]: string[]; }'.
// ❌ Property 'sandwiches' does not exist on type 'string'

const stringKey = 'milkshakes'
example.filters.arrayValues[stringKey].filter((item: string) => item !== 'choc') 
// ❌ Element implicitly has an 'any' type because expression of type '"milkshakes"' can't be used to index type 'string | { [key: string]: string[]; }'.
// ❌ Property 'milkshakes' does not exist on type 'string | { [key: string]: string[]; }'

example.filters.randomString = 'bye'
// ❌ Property 'randomString' does not exist on type '{ arrays: { [key: string]: string[]; }; } | { [key: string]: string; }'.
// ❌ Property 'randomString' does not exist on type '{ arrays: { [key: string]: string[]; }; }

我希望 TypeScript 能够理解我在 FiltersStateType 中指定的这些对象中的类型。

你知道为什么会这样吗?

最佳答案

这是由于突出显示的联合而发生的:

export type FiltersStateType = {
  filters:
    | {
        arrayValues: {
          [key: string]: Array<string>
        }
      }
    | { [key: string]: string } // this one
// ---^^^^^^^^^^^^^^^^^^^^^^^^^---
}

由于您在联合中指定了 { [key: string]: string },因此以下对象有效:

const example: FiltersStateType = {
  filters: {
    arrayValues: 'hello',
  },
}

TypeScript 无法强制 arrayValues 键的值的形状,因为 { [key: string]: string } 本身意味着任何键都可以具有字符串值.理想情况下,您必须像这样更改类型定义的结构:

// this is just an example, you should
// restructure as per your requirements 
type FiltersStateType = {
  filters: { [key: string]: string },
  arrayValues: { [key: string]: Array<string> }
}

关于arrays - 属性在类型上不存在/不能用作索引类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71576365/

相关文章:

c - 如何将 float 数组复制到结构中的 float 数组

javascript - 如何动态使用访问数组?

javascript - Angular BehaviorSubject 不发送下一个

javascript - 无法绑定(bind)到 'ngModel',因为它不是 'input' 的已知属性

javascript - 如何使用 jQuery 遍历数组数组?

arrays - MongodB $从数组中只拉一个元素

c - C中Heap实现中的BubbleUp方法

css - 可以在 Ionic 2 中的图像之间制作淡入淡出动画

javascript - 为什么在使用日期对象创建日期时收到 "Argument of type ' Date' is not assignable to parameter of type 'string | number'“?

javascript - Angular 5 URL 路由,单击按钮并保留 url 中的查询字符串参数