[英]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.