1

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

0

3 Answers 3

2

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

1
  • This doesn't accurately model an object spread because tt needs to overwrite t, not intersect with it. Something like type Spread<A, B> = Omit<A, keyof B> & B; is more accurate. A complete solution would probably need handle cases where A or B are null or undefined (they get treated like empty objects in this case).
    – snickle
    Commented Jul 18 at 20:32
1

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

1
  • I actually thought about this but I don't like it since the type it can become not intuitive at all Commented Jun 20, 2022 at 15:38
0

taking @Radu solution, adding a little tweak for a better type hint in the IDE and replacing the order of generics (so supplying spread<t1,t2> will look like spread t1 into t2)

// expands object types one level deep
export type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;
//
type Spread<T1, T2> = Expand<
  {
    [Property in keyof T2]: T2[Property];
  } & T1
>;

type Handle = { style: React.CSSProperties; props: any; createEventHandlers: any};
type HandleNames= 'left'|'right'


// type is spreaded and more intuitive 
type HandleType = Spread<{ specific: { [key in HandleNames]: Handle } }, Handle>;

ts-playground

Not the answer you're looking for? Browse other questions tagged or ask your own question.