Home > front end >  Mark class property as a generic but of a type unknown for the moment in Typescript
Mark class property as a generic but of a type unknown for the moment in Typescript

Time:05-13

In following interface, there is linkedTitle property that contains a link to another instance of it's own interface but the type of Title<> could be different.

export interface Title<T> {
  data: {
    description: string;
    presentation: string;
    value: T;
  };
  linkedTitle: Title;
  //           ^^^^^ Generic type 'Title<T>' requires 1 type argument(s).

  name: string;
  presentation: string;
  type: number;
}

How to pass the type to linkedTitle?

CodePudding user response:

Just building on @Matthieu Riegler's comment. I guess what I want is following.

export interface Title<T = string | number| boolean> {
  data: {
    description: string;
    presentation: string;
    value: T;
  };
  linkedTitles: Title;
  name: string;
  presentation: string;
  type: number;
}

Though following solutions are also working as suggested

export interface Title<T> {
  data: {
    description: string;
    presentation: string;
    value: T;
  };
  linkedTitles: Title<unknown>;
  name: string;
  presentation: string;
  type: number;
}
export interface Title<T = unknown> {
  data: {
    description: string;
    presentation: string;
    value: T;
  };
  linkedTitles: Title;
  name: string;
  presentation: string;
  type: number;
}
  • Related