【发布时间】:2021-03-22 17:24:16
【问题描述】:
我有以下键值对,它被用于过滤系统。当我们应用一个过滤器时,我们可以将它与所有当前的过滤器合并,或者只是应用它并重置以前的过滤器。
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 类型之一,但它会抛出上面的错误。
为什么会这样?
【问题讨论】:
-
请分享可重现的例子
-
感谢@31piy,问题得以解决。正如他所说,我们可以这样做:
[key in PossibleFilterKeys]?: string,但我们也可以使用 Partial 实用程序:apply: (filter: Partial<Filter>) => void
标签: typescript