Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Type in TypeScript

Tags:

typescript

How can I dynamically assign a type to a generic class based on the type variable's property? For example

interface EntityErrors<T> {
    [p in keyof T]?: string; // How can I make "string" dynamic?  It needs to be a string for primitives (id, name), and an array of strings for the `teachers` array.

    // I've tried the following, but it appears `teachers` is still resolving to `SimpleError` instead of `ArrayOfErrors`.
    [p in keyof T]?: p extends [] ? ArrayOfErrors<p> : SimpleErrors;
    // I've also tried `instanceof` and `typeof`, but I receive syntax errors.
    [p in keyof T]?: p instanceof [] ? ArrayOfErrors<p>: SimpleErrors;
}

interface School {
    id: string;
    name: string;
    teachers: Teacher[];
}

interface Teacher {
    id: string;
    name: string;
}

Because the School error object looks like:

{
  "id": "The input is invalid",
  "name": "The input is invalid",
  "teachers": [
    {
      "id": "The input is invalid",
      "name": "The input is invalid"
    },
    {
      "id": "The input is invalid",
      "name": "The input is invalid"
    }
  ]
}

1 Answers

p is a string type with the name of the property.

You need to check the type of the property within your class:

    [p in keyof T]?: T[p] extends [] ? ArrayOfErrors<T[p]>: SimpleErrors;
like image 113
SLaks Avatar answered Sep 08 '25 23:09

SLaks