[英]Typescript: conditionally mark an object property as optional?
例如:
type Foo = {
'a': string,
'b': undefined,
};
type Bar<T extends keyof Foo> = {
foo: Foo[T],
};
const bar1: Bar<'a'> = { foo: 'a' }; // ok
const bar2: Bar<'b'> = { foo: undefined }; // ok
const bar3: Bar<'b'> = {}; // Property 'foo' is missing in type '{}' but required in type 'Bar<"b">'.
在这个例子中,我希望foo
属性是可选的,如果它的值是undefined
。 换句话说,我希望{ foo: undefined }
和{}
可以互换。
在我的实际代码中,我有有条件地返回不同字段的 API 处理程序。 如果不需要某个字段,我想省略它,而不必将其定义为undefined
。
解决此问题的一种方法是:
type Bar<T extends keyof Foo> = Foo[T] extends undefined
? { foo?: undefined }
: { foo: Foo[T] };
但是,如果很多字段是可选的,则条件可能会变得很长。 有没有更好的办法?
type Foo = {
'a': string,
'b': undefined,
}
type Bar<T extends keyof Foo> = {
propOne: Foo[T],
propTwo: Foo[T]
};
type UndefinedBarKeys<T extends keyof Foo> = {
[K in keyof Bar<T>]: Bar<T>[K] extends undefined ? K : never
}[keyof Bar<T>];
type BetterBar<T extends keyof Foo> =
Foo[T] extends undefined
? { [K in keyof Pick<Bar<T>, UndefinedBarKeys<T>>]?: Foo[T] }
: Bar<T>;
const bar1: BetterBar<'a'> = { propOne: 'asdf', propTwo: 'qwerty'};
const bar2: BetterBar<'b'> = { propOne: undefined, propTwo: undefined };
const bar3: BetterBar<'b'> = {};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.