Home > Enterprise >  Spreading keys of an interface inside another type in typescript
Spreading keys of an interface inside another type in typescript

Time:11-13

I have some types like this:

export interface PublicFileData {
  bucketName?: string;
  objectName?: string;
}
export interface PrivateFileData {
  id: string;
}
// Above types are imprted from other packages

export type Storage =
  | { type: "public"; data: PublicFileData }
  | { type: "private"; data: PrivateFileData };

It works. But how can I change it to be a flat object like this without knowing FileData types?:

export type Storage =
  | {
      type: "public";
      bucketName?: string;
      objectName?: string;
    }
  | { 
      type: "private"; 
      id: string 
    };

I cannot do this manually because FileData types are imported from some where else

Maybe I need a missing Spread Type Operator!!!

// I wish I had something like this:
export type Storage =
| { type: "public"; ...PublicFileData }
| { type: "private"; ...PrivateFileData };

How this is possible in typescript?

CodePudding user response:

with an intersection:

export type Storage =
  | ({ type: "public"} & PublicFileData )
  | ({ type: "private"} & PrivateFileData );
  • Related