mohsen saremi
mohsen saremi

Reputation: 715

Typescript merge types

I have type A and type 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

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

Upvotes: 3

Views: 981

Answers (2)

Aleksey L.
Aleksey L.

Reputation: 38046

This is because kind can't be of type "A" and "B" at the same type.

Ways to fix:

1. Generics:

type WithKind<T extends string> = {
    kind: T,
    value: string,
    value2: string,
    value3: string,
}

type A = WithKind<"A">;

type B = WithKind<"B">;

2. Omit:

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

Upvotes: 4

Etheryte
Etheryte

Reputation: 25321

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">;

Upvotes: 4

Related Questions