我想要一个可以在其根中包含字符串的对象,并在 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/