Home > Software engineering >  typescript mimic spread operator on typescript type
typescript mimic spread operator on typescript type

Time:06-20

I want to mimic the behavior of the spread operator on types. so for example type tt = {...{t1:number},t2:number} => type tt = {t1:number,t2:number}

Goal: reuse t t={t1:any; t2:any} on type tt = { t1:any; t2:any; specific:{t1:any; t2:any} }, preferably like how { ...t; specific:t } could have worked (in reality it is much more complex type)

possible solutions:

  • type tt = { t1:any; t2:any; specific:tt }; - works but nested is allowed unintentionally(tt.specific.t1 is wanted but tt.specific.t1.specfic is not).

  • another option that does not work.

    type t = { t1: any; t2: any;}
    type tt = { [key in keyof t]: t[key], specific: tt };
    //                                  ^ this is not allowed when {[...]:...} is used
    

Typescript spread operator for type is not a duplicate

CodePudding user response:

You can use Intersection Types to achieve the result you want

type t = { t1: any; t2: any;}

type tt = t & { specific?: tt };

Here is the link to TS Playground with the example

CodePudding user response:

Along side what @dzianis wrote, which is a very good solution you could also do something like this:

type tt = {
 t1: number
 t2: number
}

type Spread <T1, T2> = {
    [Property in keyof T1]: T1[Property]
} & T2

let combined: Spread<tt, {t3: boolean}> = {
    t1: 23,
    t2: 423,
    t3: false
}

This has little value on its own (it's just a more convoluted Intersection Types) but gives you more options in the future. You could be removing readonly from some types or exclude some of the keys, or even renaming them.

A playground can be found here

  • Related