【发布时间】:2020-09-26 13:12:59
【问题描述】:
我想输入一个允许默认值的数据库插入函数: (我正在使用 type-fest 的 SetOptional)
function defaultInsert<T, D = Partial<T>>(data: SetOptional<T, keyof D>, defaults: D) {
我想对 SetOptional 说的是,数据对象应该包含 T 中的任何内容,而不是在默认值 (D) 中指定,但它可以覆盖默认值中的任何内容。
不幸的是,这导致了以下错误
Type 'keyof D' does not satisfy the constraint 'keyof T'.
Type 'string | number | symbol' is not assignable to type 'keyof T'.
Type 'string' is not assignable to type 'keyof T'.(2344)
Typescript playground 获取更详细的示例。
有什么方法可以过滤 Partial 以仅包含 T 的键,因为我假设这是由于 D 可能包含不在 T 中的多余属性而导致的问题?
非常感谢
编辑:作为@Alex Chashin 的建议,另一个 TS Playground 使用键作为定义默认值的方式。
EDIT2:使用 UPD2 @Alex Chashin 中提供的解决方案更新了 playground
EDIT3:更新了前面的示例,以便也可以省略默认值:playground
【问题讨论】:
标签: typescript keyof