我想要一个对象,它可以在其根目录下包含字符串,并在arrayValues对象中包含字符串数组。这是将在应用程序中使用的配置对象。
此对象及其键将是动态的(通过用户状态值定义),因此我无法根据特定键名称指定类型。
我将从应用程序的一部分向“arrayValues”添加数组,从另一部分向“filters”添加字符串。
然而,当访问对象属性时出现了错误:
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 中指定的对象类型,但它似乎不能。你知道这是为什么吗?
sandwiches
。这就是为什么TS会阻止你,因为使用可能是正确的,也可能是不正确的。 - VLAZ