gpt4 book ai didi

typescript 既不是,也不是,但不是两个属性

转载 作者:行者123 更新时间:2023-12-05 01:28:43 27 4
gpt4 key购买 nike

我想断言一个类型可以既没有也没有,但不能同时拥有一对属性。

以下内容不起作用,尽管我认为它会起作用。显然有 a: neverb: never 意味着我必须同时提供两者?

我还尝试使用 {} 代替编译和运行的 NeitherANorB,但没有发现我错误地传递了两个选项的第四种情况。

interface JustA {
a: string;
b: never;
}

interface JustB {
a: never;
b: string;
}

interface NeitherANorB {
a: never;
b: never;
}

type NotBothAAndB = JustA | JustB | NeitherANorB;

function testMe(x: NotBothAAndB) {
console.log(x);
}

testMe({}); // OK
testMe({ a: "HI!" }); // OK
testMe({ b: "SUP?" }); // OK
testMe({ a: "HI!", b: "SUP?" }); // NOT OK

最佳答案

您可以使用 {property?: never}{property?: undefined} 来表示属性不应存在。请注意,即使在前一种情况下,只要该属性具有值 undefined 就允许存在,因为这正是 Typescript 处理可选属性的方式。所以这应该做你想做的:

type NotBoth =
| {a: string, b?: never}
| {a?: never, b: string}
| {a?: never, b?: never}

// ok
const test1: NotBoth = {a: 'foo'};
const test2: NotBoth = {b: 'bar'};
const test3: NotBoth = {};
// error: 'string' is not assignable to 'undefined'
const testFail: NotBoth = {a: 'foo', b: 'bar'};

Playground Link

为方便起见,这里有一个辅助类型,用于构造这样的联合,其中最多允许使用某些属性中的一个:

// Simplify<T> just makes the resulting types more readable
type Simplify<T> = T extends infer S ? {[K in keyof S]: S[K]} : never
type NoneOf<T> = Simplify<{[K in keyof T]?: never}>
type AtMostOneOf<T> =
| NoneOf<T>
| {[K in keyof T]: Simplify<Pick<T, K> & NoneOf<Omit<T, K>>>}[keyof T]

type NotBoth = AtMostOneOf<{a: string, b: string}>

Playground Link

关于 typescript 既不是,也不是,但不是两个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68399257/

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