I have implemented the NoInfer
feature from the library called ts-toolbelt.
However, it seems that the example provided below does not reflect its intended effect.
In this scenario, the generic type is deduced from the util
function as soon as it is introduced.
Observations include:
- For
demo1
, no function argument is utilized resulting in a type of:{ foo: string }
- For
demo2
, a function argument_
is introduced leading to the type being inferred asunknown
Is there a method to enforce that the generic type is exclusively inferred from the return value so that demo2
shares the same type as demo1
?
type NoInfer<T> = [T][T extends any ? 0 : never];
function factory<T>(generator: (util: (u: NoInfer<T>) => void) => T): T {
return {} as any;
}
const demo1 = factory(() => {
return {
"foo": "bar"
}
})
const demo2 = factory((_) => {
return {
"foo": "bar"
}
})
// works
demo1.foo = "baz";
// ERROR! demo2 is unknown
demo2.foo = "baz";