gpt4 book ai didi

javascript - typescript :有条件地将对象属性标记为可选?

转载 作者:行者123 更新时间:2023-12-05 06:58:09 24 4
gpt4 key购买 nike

例如:

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

在这个例子中,我希望 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'> = {};

关于javascript - typescript :有条件地将对象属性标记为可选?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64703742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com