[英]Typescript: conditionally mark an object property as optional?
Eg:例如:
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">'.
TS Playground: https://www.typescriptlang.org/play?#code/C4TwDgpgBAYg9nKBeKBvAUFLUDkBDHALigGdgAnASwDsBzAGk2xwCMioBXagEwgDMaEbowC+AbnTpQkKACE85ADwAVKBAAewCDxJQA1hBBw+sBAD5kaJlj4Ji8OAG1lAXVET0AYzjUyUFgoAjMTySvg4FiioULZwxOFQ4l4+fgHkAEwhCoqsEZbRscRcvALUQokS3r7A-goAzFlhbJFo4kA TS游乐场: https://www.typescriptlang.org/play?#code/C4TwDgpgBAYg9nKBeKBvAUFLUDkBDHALigGdgAnASwDsBzAGk2xwCMioBXagEwgDMaEbowC+AbnTpQkKACE85ADwAVKBAAewCDxJQA1hBBw+sBAD5kaJlj4Ji8OAG1lAXVET0AYzjUyUFgoAjMTySvg4FiioULZwxOFQ4l4+fgHkAEwhCoqsEZbRscRcvALUQokS3r7A-goAzFlhbJFo4kA
In this example, I want the foo
property to be optional if its value is undefined
.在这个例子中,我希望
foo
属性是可选的,如果它的值是undefined
。 In other words, I want { foo: undefined }
and {}
to be interchangeable.换句话说,我希望
{ foo: undefined }
和{}
可以互换。
In my actual code, I have API handlers that conditionally return different fields.在我的实际代码中,我有有条件地返回不同字段的 API 处理程序。 If a field is not needed, I want to omit it instead of having to define it as
undefined
.如果不需要某个字段,我想省略它,而不必将其定义为
undefined
。
One way to fix this is:解决此问题的一种方法是:
type Bar<T extends keyof Foo> = Foo[T] extends undefined
? { foo?: undefined }
: { foo: Foo[T] };
However, if a lot of fields are optional, then the conditional can become very long.但是,如果很多字段是可选的,则条件可能会变得很长。 Is there a better way?
有没有更好的办法?
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.