B
B
BuckvicK2022-02-07 14:10:21
typescript
BuckvicK, 2022-02-07 14:10:21

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

1 answer(s)
W
WbICHA, 2022-02-07
@BuckvicK

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(),
  },
];

https://www.typescriptlang.org/play?#code/JYOwLgpg...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question