Typescript类型别名允许可选接口

问题描述 投票:0回答:1

我正在尝试在我的打字稿代码中创建一个新类型,如下所示:

interface required {
  x: string
}

interface optional1 {
  y: string
}

interface optional2 {
  z: string
}

type combined = required & (optional1 | optional2)

我想要的行为是:

  • 绝对应该存在所需接口的属性。
  • 如果有其他属性,则必须符合optional1或optional 2
typescript interface type-alias
1个回答
2
投票

您需要在可选接口中将属性标记为可选,方法是使用?

如果你这样做,你的定义是有效的,除了允许一个对象同时具有yz属性(type combined = (required & optional1) | (required & optional2);也是如此,这让我感到惊讶):

interface required {
  x: string
}

interface optional1 {
  y?: string               // Note the ?
}

interface optional2 {
  z?: string               // Note the ?
}

type combined = required & (optional1 | optional2);

function foo(x: combined): void {

}

foo({ x: "x" });                 // Works
foo({ x: "x", y: "y" });         // Works
foo({ x: "x", y: "y", z: "z" }); // Works
foo({ x: "x", q: "q" });         // Error because of q
foo({ y: "y" });                 // Error because there's no x

Playground Link

© www.soinside.com 2019 - 2024. All rights reserved.