如何使用Typescript

时间:2020-05-14 11:06:25

标签: typescript

我正在构建一个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;
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:-1)

因为检查在两个接口之间是通用的。为什么不

echo-ing

相反?

相关问题