typescript - TypeScript 中的动态类型

标签 typescript

如何根据类型变量的属性将类型动态分配给泛型类?例如

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

因为 School 错误对象看起来像:

{
  "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"
    }
  ]
}

最佳答案

p 是一个带有属性名称的字符串类型。

您需要检查类中属性的类型:

    [p in keyof T]?: T[p] extends [] ? ArrayOfErrors<T[p]>: SimpleErrors;

关于typescript - TypeScript 中的动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53962453/

相关文章:

javascript - react-native-svg 中 <Rect/> 的动画宽度

javascript - Google Chrome 中的源映射是否会推送到 Error.stack

android - 如何将文本(字符串)插入 ion-textarea?

reactjs - react 和 typescript 与 webpack 打字问题

javascript - Angular 5 - react 形式 - 有没有办法使用变量来修补值?

typescript 错误 "Cannot find name ' 需要'。并且找不到名称 'process'。”

angular - Ionic - 类别的水平滚动选项卡

typescript - Vue typescript 递归组件

typescript - vue文件上传——连续上传同一个文件

javascript - typescript 返回解构?