打字稿:至少需要一个属性的打字稿

时间:2020-03-27 07:52:50

标签: javascript typescript

请考虑我具有以下类型:

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

这里是2个对象的并集类型的类型:

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

Typescript将要求对象的类型与此联合中的类型之一兼容。 Here is solution in playground

注意:如果您确实只有两个属性,这是最简单的解决方案。