TypeScript: Optional merge types

Viewed 1130

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?

2 Answers

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'}
Related