如何在TypeScript中创建耦合类型

huangapple go评论62阅读模式
英文:

How to create coupled types in Typescript

问题

我有四种类型,分别是 A、B、X 和 Y。在我的情况下,A 和 X 只能一起使用,B 和 Y 也只能一起使用。我要如何创建一种类型/接口,使我能够编写以下代码:

value: MyInterface = {a: A, x: X},
value: MyInterface = {a: B, x: Y},

但不能编写以下代码:

value: MyInterface = {a: A, x: Y},
value: MyInterface = {a: B, x: X},
英文:

I have four types, lets say A and B, and X and Y. In my case, A and X are only used together, and B and Y are only used together. How can i achieve a type/interface that lets me write this:

value: MyInterface = {a: A, x: X},
value: MyInterface = {a: B, x: Y},

but not this:

value: MyInterface = {a: A, x: Y},
value: MyInterface = {a: B, x: X},

答案1

得分: 2

你可以使用联合类型来实现这个。

type A = string
type X = string[]

type B = number
type Y = number[]

type MyInterface = { a: A, x: X } | { a: B, x: Y }

const test1: MyInterface = { a: 'foo', x: ['bar', 'foobar'] } // 通过
const test2: MyInterface = { a: 0, x: [1, 2] } // 通过
const test3: MyInterface = { a: 0, x: ['', ''] } // 错误
const test4: MyInterface = { a: '', x: [1, 2] } // 错误
英文:

You can use union type for this

type A = string
type X = string[]

type B = number
type Y = number[]

type MyInterface = { a: A, x: X } | { a: B, x: Y }

const test1: MyInterface = { a: 'foo', x: ['bar', 'foobar'] } // pass
const test2: MyInterface = { a: 0, x: [1, 2] } // pass
const test3: MyInterface = { a: 0, x: ['', ''] } // error
const test4: MyInterface = { a: '', x: [1, 2] } // error

Playground

答案2

得分: 0

Types would allow MyInterface (MyType) to become a Union type.

type AX = {
  a: A;
  x: X;
};
type BY = {
  b: B;
  y: Y;
};

type MyType = AX | BY;

const value: MyType = {
  a: "a",
  x: "x",
};
英文:

Types would allow MyInterface (MyType) to become a Union type.

type AX = {
  a: A;
  x: X;
};
type BY = {
  b: B;
  y: Y;
};

type MyType = AX | BY;

const value: MyType = {
  a: "a",
  x: "x",
};

huangapple
  • 本文由 发表于 2023年5月15日 01:33:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76248855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定