【发布时间】:2019-02-02 03:51:46
【问题描述】:
如何创建一个 kinda-Partial<T> 类型,不允许 undefined 值?
这是一个例子:
interface MyType {
foo: string
bar?: number
}
const merge = (value1: MyType, value2: KindaPartial<MyType>): MyType => {
return {...value1, ...value2};
}
const value = {
foo: 'foo',
bar: 42
}
merge(value, {}); // should work
merge(value, { foo: 'bar' }); // should work
merge(value, { bar: undefined }); // should work
merge(value, { bar: 666 }); // should work
merge(value, { foo: '', bar: undefined }); // should work
merge(value, { foo: '', bar: 666 }); // should work
// now the problematic case:
merge(value, { foo: undefined }); // this should throw an error
// because MyType["foo"] is of type string
我正在寻找的类型应该:
- 只接受存在于泛型类型上的键(就像普通的
Partial<T>) - 接受泛型键的子集
-
但如果泛型类型不接受
undefined作为该键,则不接受undefined
这可能吗?
编辑:我还在 TypeScript 存储库中创建了一个问题,因为这很奇怪,应该在某个时候抛出错误:https://github.com/Microsoft/TypeScript/issues/29701
【问题讨论】:
-
请记住,这样做可能会使您的代码更难以编程方式使用;你会禁止例如
update(value: MyType, new_foo_val?: string) { return merge(value, { foo: new_foo_val }).
标签: typescript generics partial