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"
}
]
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With