gpt4 book ai didi

typescript - 如何使用 Typescript 根据值创建动态类型

转载 作者:行者123 更新时间:2023-12-04 04:10:39 25 4
gpt4 key购买 nike

我正在构建一个 React 组件,该组件将根据用户传递的属性具有不同的 HTML 标记。下面是一个例子:

interface Common {
common?: number;
}

interface A extends Common {
first?: string;
second?: string;
check: true;
}

interface B extends Common {
third?: string;
fourth?: string;
check?: false;
}

type Test = A | B;

为了测试这一点,我期待以下内容:

// Success
let test: Test = {
common: 1,
check: true,
first: "text"
}
// Success
let test: Test = {
common: 1,
check: false,
third: "text"
}
// Fail
let test: Test = {
common: 1,
check: true,
third: "text"
}
// Fail
let test: Test = {
common: 1,
check: false,
first: "text"
}

所有这些都在工作,挑战是在不传递值的情况下获得类型 B 来检查,如下所示:

let test: Test = {
common: 1,
first: "text", // should highlight an error because `check` is not passed
third: "text",
}

这是我尝试过的:

// Attempt 1: is to include possible values
interface B extends Common {
third?: string;
fourth?: string;
check?: false | null | undefined | never | unknown | void; // tried them all
}

// Attempt 2: is not to include at all. Still didn't work
interface B extends Common {
third?: string;
fourth?: string;
}

最佳答案

那是因为A | B包含 OR,但您需要 exclusive OR .您可以使用 npm package ts-xor .

关于typescript - 如何使用 Typescript 根据值创建动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61795818/

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