The Cubear Guy
The Cubear Guy

Reputation: 381

TypeScript: Optional merge types

I have type a and type b, but this should work with any amount of types.

type a = {
    first: number
}

type b = {
    second: string
    third: string
}

I want to create a type that optionally merges all those types, so if it would have the second field, it should have the third field also, but it doesn't have to have them both:

Good:

const aa = {
     first: 1,
     second: "hi",
     third: "hello"
}

const ab = {
     first: 1
}

const ac = {
     second: "hi",
     third: "hello"
}

Bad:

const bb = {
     first: 1,
     second: "hi"
}

How could I define such a type?

Upvotes: 7

Views: 3523

Answers (2)

Lesiak
Lesiak

Reputation: 26094

type None<T> = {[K in keyof T]?: never}
type EitherOrBoth<T1, T2> = T1 & None<T2> | T2 & None<T1> | T1 & T2

type abcombined = EitherOrBoth<a,b>

See more elaborated example at: Can Typescript Interfaces express co-occurrence constraints for properties

Playground link

Upvotes: 13

Karan Kumar
Karan Kumar

Reputation: 3186

I am not sure if you could do that. This is what I would do :

You could use "|" operator while defining a variable.

type a = {
    first: number
}

type b = {
    second: string
    third: string
}

const test: a | b ={ first: 3, second: 'string'}

Upvotes: 0

Related Questions