gpt4 book ai didi

javascript - Typescript:需要至少一个属性的类型

转载 作者:行者123 更新时间:2023-12-02 21:19:38 33 4
gpt4 key购买 nike

考虑我有以下类型:

type SomeType = {
propOne: any;
propTwo: any;
propThree: any;
}

propOne为必填项,propTwopropThree是可选的,但至少其中之一是必需的。如何定义具有该约束的类型?

// The following code is my expectation
let someVar1: SomeType = { propOne: 1, propTwo: "two" } //Okay
let someVar2: SomeType = { propOne: 1, propThree: "three" } //Okay
let someVar3: SomeType = { propOne: 1, propTwo: "two", propThree: "three" } //Okay
let someVar4: SomeType = { propOne: 1 } //Not Okay

最佳答案

即使在编辑后,您也可以使用相同的技巧:

type SomeType = {
propOne: number;
propTwo?: string;
propThree?: string;
} & ({
propTwo: string;
} | {
propThree: string;
})

let someVar1: SomeType = { propOne: 1, propTwo: "two" } //Okay
let someVar2: SomeType = { propOne: 1, propThree: "three" } //Okay
let someVar3: SomeType = { propOne: 1, propTwo: "two", propThree: "three" } //Okay
let someVar4: SomeType = { propOne: 1 } //Not Okay

function f(s: SomeType) {
let p1 = s.propOne; // number
let p2 = s.propTwo; // string | undefined
let p3 = s.propThree; // string | undefined
}

它强制您在声明时至少拥有一个属性,并且允许您在使用该类型的对象时同时使用该类型的两个属性。

Playground

关于javascript - Typescript:需要至少一个属性的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60881882/

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