属性'sandwiches'在类型 'string' 上不存在



我想要一个可以包含字符串或字符串数组的对象。全部使用字符串键。这是一个将在应用程序中使用的配置对象。

这个对象将是动态的(用户定义的状态值(,所以我无法根据特定的键名指定类型。这就是为什么我使用索引签名,因为我不知道密钥是什么。我将从应用程序的一部分添加数组,从另一部分添加字符串。

我得到的错误如下所示:

TS游乐场

type FiltersStateType = {
filters: { [key: string]: Array<string> | string }
}
const example: FiltersStateType = {
filters: {
sandwiches: ['ham', 'cheese'],
milkshakes: ['choc', 'banana'],
randomString: 'hello',
},
}
example.filters.sandwiches.filter(item => item !== 'ham')
// ❌ Property 'filter' does not exist on type 'string | string[]'.
// ❌ Property 'filter' does not exist on type 'string'
// do I need to type narrow every time to discern between string and string[]?
if (Array.isArray(example.filters.sandwiches)) {
example.filters.sandwiches.filter(item => item !== 'ham')
}

我想这是因为TS不知道它是字符串还是数组。我是否需要每次都键入"窄"来区分字符串和字符串[]?

if (Array.isArray(example.filters.sandwiches)) {
example.filters.sandwiches.filter(item => item !== 'ham')
}

我可以建议您使用此示例。[key: string]: Array<string> | string;行用于将来可以添加的特性。在我列出需求属性及其类型之后。主要的问题是,您不能组合多个类型,然后访问两个类型中都不包含的属性。例如,我没有列出randomString属性,但我可以很容易地访问它的第n个元素,因为arraystring都有这个属性

type FiltersStateType = {
filters: {
[key: string]: Array<string> | string;
sandwiches: string[];
milkshakes: string[];
}
}
const example: FiltersStateType = {
filters: {
sandwiches: ['ham', 'cheese'],
milkshakes: ['choc', 'banana'],
randomString: 'hello',
},
}
example.filters.sandwiches = example.filters.sandwiches.filter(item => item !== 'ham')
console.log(example.filters.sandwiches);
console.log(example.filters.randomString[1]);

或者您可以使用as关键字:

type FiltersStateType = {
filters: {
[key: string]: Array<string> | string;
}
}
const example: FiltersStateType = {
filters: {
sandwiches: ['ham', 'cheese'],
milkshakes: ['choc', 'banana'],
randomString: 'hello',
},
}
example.filters.sandwiches = (example.filters.sandwiches as string[]).filter(item => item !== 'ham')
console.log(example.filters.sandwiches);
console.log(example.filters.randomString[1]);

抱歉在SO代码段中,由于as string[],我无法运行

相关内容

最新更新