7

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?

1
  • Are you looking for XOR merging? Commented Sep 11, 2020 at 22:02

2 Answers 2

13
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

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, this is very helpful! Just can the EitherOrBoth type be applied to more than two types?
Yes, you can pass another EitherOrBoth as a type argument. Check linked questions for example.
Thank you! This solves my problem. I've checked the linked question, could the CombinationOf type be applied to any number of types?
The definition in linked question has up to four types, but it is easy to extend it if you need more.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.