Answer the question
In order to leave comments, you need to log in
How to type a function argument inside an interface that depends on an interface field?
Good afternoon, there is such a code and the question is how to type the argument in the showValue function (what to specify instead of any ) so that when using it in object A , this would be adequately tracked by typescript:
interface Row<P> {
field: keyof P;
showValue?: (value: any) => string;
}
interface Data {
name?: string;
age?: number;
}
const A: Row<Data>[] = [
{
field: "age",
// Здесь value должен иметь тип number
showValue: (value) => value.toString(),
},
{
field: "name",
// Здесь value должен иметь тип string
showValue: (value) => value.toString(),
},
];
Answer the question
In order to leave comments, you need to log in
interface Row<T, K extends keyof T> {
field: K;
showValue?: (value: T[K]) => string;
}
interface Data {
name?: string;
age?: number;
}
type AData<T> = {
[K in keyof T]: Row<T, K>;
}[keyof T]
const A: AData<Data>[] = [
{
field: "age",
// Здесь value должен иметь тип number
showValue: (value) => value.toString(),
},
{
field: "name",
// Здесь value должен иметь тип string
showValue: (value) => value.toString(),
},
];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question