[英]Typescript merge types
I have type A
and type B
我有
A
型和B
型
type A = {
kind: "A",
value: string,
value2: string,
value3: string,
};
type B = { kind: "B" } & A ;
I want to type B
has all the properties of type A
but with different kind
value我想键入
B
具有类型A
所有属性,但具有不同的kind
值
But when I write this但是当我写这个
const temp: B = {
kind: "B",
value: "X",
value2: "X2",
value3: "X3",
};
I get this error我收到这个错误
TS2322 type
string
is not assignable to typenever
TS2322 类型
string
不可分配给类型never
This is because kind can't be of type "A" and "B" at the same type.这是因为 kind 不能是同一类型的“A”和“B”类型。
Ways to fix:修复方法:
1. Generics: 1. 泛型:
type WithKind<T extends string> = {
kind: T,
value: string,
value2: string,
value3: string,
}
type A = WithKind<"A">;
type B = WithKind<"B">;
2. Omit: 2.省略:
type B = Omit<A, "kind"> & { kind: "B" } ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.