rostamiani
rostamiani

Reputation: 3265

Spreading keys of an interface inside another type in typescript

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?

Upvotes: 1

Views: 120

Answers (1)

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21474

with an intersection:

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

Upvotes: 2

Related Questions