我有以下键值对,它被用于过滤系统。当我们应用过滤器时,我们可以将它与所有当前过滤器合并,或者只是通过重置以前的过滤器来应用它。
type MINE = "mine"
type BOOKMARKED = "bookmarked"
type TEXT_QUERY = "textQuery"
type JobType = "type"
export type PossibleFilterKeys = MINE | BOOKMARKED | TEXT_QUERY | JobType
type Filter = {
[key in PossibleFilterKeys]: string;
};
然后我有以下函数原型:
const apply = (filter: Filter) => void
当我们使用它时:
// name: PossibleFilterKeys,
// value: string,
apply({[name]: value})
它触发: TS2345: Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'Filter'. Type '{ [x: string]: string; }' is missing the following properties from type 'Filter': mine, bookmarked, textQuery, type
我想应用一个过滤器,它的键可能是其中一种PossibleFilterKeys
类型,但它会抛出上面的错误。
为什么会发生这种情况?
问题在于这个声明:
type Filter = {
[key in PossibleFilterKeys]: string;
};
以上声明Filter
必须包含PossibleFilterKeys
. 您可以通过以下语法将它们设为可选:
type Filter = {
[key in PossibleFilterKeys]?: string; // <-- Place a question mark
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句