简体   繁体   English

打字稿合并类型

[英]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 type never TS2322 类型string不可分配给类型never

Your problem stems from the fact that你的问题源于这样一个事实

"A" & "B" === never

If you want to override a fixed string value with a new one, you can Omit it first.如果你想用一个新的值覆盖一个固定的字符串值,你可以先省略它。

type B = { kind: "B" } & Omit<A, "kind">;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM