简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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