gpt4 book ai didi

typescript - TypeScript 中的动态类型

转载 作者:行者123 更新时间:2023-12-05 02:14:10 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com