简体   繁体   中英

Typescript - optional type if generic is not provided

I Would like optionalFields to have type of OptionalFieldsByTopic<Topic> if generic is not provided, otherwise OptionalFieldsByTopic<T> . Thanks for help in advance.

export interface ICreateItem<T extends Topic = never> { // T must be optional
   id: string;
   name: string;
   tags: string[];
   collectionId?: string;
   topic: string;
   optionalFields?: OptionalFieldsByTopic<T>; // If T is not provided then this is equal OptionalFieldsByTopic<Topic>
}

type OptionalFieldsByTopic<T extends keyof IOptionalFields> = IOptionalFields[T];

OptionalFIeldsByTopic example:

const test: OptionalFieldsByTopic<"books"> = { author: "brandon", language: "english" }

export type Topic = keyof IOptionalFields;

mockup data:


export interface IOptionalFields {
   books: {
      author?: string;
      language?: string;
      translation?: string; 
   };
   vehicle: {
      model?: string;
      type?: string;
      color?: string;
 
   };
   painting: {
      author?: string;
      description?: string;
      image?: string;
   };
}


This should work:

export interface ICreateItem<T extends Topic = Topic> {
...
 }

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