1

The idea I have feels pretty simple but somehow I'm stuck and wondering if I'm missing something obvious.

Consider a type like this:

type GenericField<T> = {
  value: T;
  onChange(value: T): void;
}

I would like to be able to declare an instance of type GenericField without having to specify T, as it could be inferred from the value.

const field: GenericField = { // Error: Generic type 'GenericField' requires 1 type argument(s).
  value: new Date(),
  onChange: (value) => { // I want value to be inferred as a Date here
    // ...
  },
};

The goal would be to be able to easily declare an array of these items with guaranteed type safety.

const fields: GenericField<unknown>[] = [
  {
    value: new Date(),
    onChange: (value: Date) => { // I have to explicitly declare the type here otherwise it is "unknown", even though it could only be a Date
      // ...
    },
  },
]

Is any of this possible or the generic type always has to be specified? I've already searched a lot but could only find solutions for very different scenarios. Any input is appreciated.

tiagodws
  • 1,345
  • 13
  • 20
  • It is possible to do only with help of an extra function. Here you can find more examples https://catchts.com/infer-arguments – captain-yossarian from Ukraine Oct 17 '21 at 20:14
  • Possible duplicate of https://stackoverflow.com/questions/62487613/typing-an-array-of-generic-inferred-types – jcalz Oct 17 '21 at 20:25
  • Does [this code](https://tsplay.dev/wEDnvW) meet your needs? If so then this is essentially a duplicate of the other question; if not, please [edit] your example code into something that demonstrates use cases the generic array fails to satisfy. – jcalz Oct 17 '21 at 20:43
  • If you know upfront your generics, you can use this https://stackoverflow.com/questions/67337050/typescript-failing-to-correctly-infer-types-from-generic-using-keyof-as-property#answer-67337548 – captain-yossarian from Ukraine Oct 18 '21 at 08:44

0 Answers0