0

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


3
  • I Would like to optionalFields to be type of Topic if generic is not provided. That makes no sense to me, can you elaborate? Commented Aug 6, 2022 at 9:50
  • I edited post. Hope it makes more sense now. Commented Aug 6, 2022 at 9:55
  • 1
    So it's T that should have default type Topic, not optionalFields. What's the problem with interface ICreateItem<T extends Topic = Topic>? Commented Aug 6, 2022 at 10:00

1 Answer 1

1

This should work:

export interface ICreateItem<T extends Topic = Topic> {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.