Let’s assume having the following made-up example given.
interface Type<T> extends Function {
new (...args: any[]): T;
}
interface ControlValueAccessor<T> {
writeValue(value: T): void
}
function factory<T extends ControlValueAccessor<V>, V>(component: Type<T>) {
return (value: V) => `${value}`;
}
class MyComponent implements ControlValueAccessor<string> {
public writeValue(value: string): void {}
}
const fn = factory(MyComponent)
I would expect that the type of fn
is correctly inferred as (value: string) => string
, but it is inferred as (value: unknown) => string
.
Is it possible to correctly infer the type, hence that unknown
is exchanged with string
?
1
It seems that the following adjustments are a solution:
type ExtractType<T> = T extends ControlValueAccessor<infer V> ? V : never;
function factory<T extends ControlValueAccessor<unknown>>(component: Type<T>) {
return (value: ExtractType<T>) => `${value}`;
}
Feel free to mention further alternatives.