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.