英文:
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
答案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",
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论