我想要一个在其根中可以包含字符串的对象,以及arrayValues对象中的字符串array.这是一个将在应用程序中使用的配置对象.
这个对象及其键将是动态的(通过用户状态值定义),因此我无法根据特定的键名指定类型.
我将从应用程序的一个部分向"ArrayValue"添加数组,从应用程序的另一个部分向"filters"添加字符串.
However I'm getting errors when accessing object properties:
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中指定的那样.
你知道为什么会这样吗?