Home > Software engineering >  Typescript - optional type if generic is not provided
Typescript - optional type if generic is not provided

Time:08-06

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;
   };
}


CodePudding user response:

This should work:

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