adplus-dvertising

how to use infer to infer the return type of a void function?

Asked 2 days ago
Viewed 9 times

I'm trying to better understand using infer keyword in typescript.

Would this be a valid demonstration on using infer properly ?

I want to just infer the return type of the following function,

const [name, setName] = useState<string>('');
const [age, setAge] = useState<number>();

type CallbackType<T> = T extends () => infer R ? R: never

function stateCallback<T>(name: string, age: number): CallbackType<T>{
  setName(name)
  setAge(age);
}

It should return a void type as im not returning anything, is this the right approach on using infer ?

Playground:

https://www.typescriptlang.org/play?ssl=9&ssc=2&pln=1&pc=1#code/MYewdgzgLgBA2mAhgWwKYBoYVVAci1AXRgF4YBXbAZSkSlQB5oAnASzAHMA+ACgHI+ASgDcAWABQoSLDiIOGLDgCC84mUqoadRmHLIARqma8REiVACeAB1QwAwogA2j-YmABrACrXGnrqRhPGFQAD3owABMIGB5BUn92ADMjGAAlGAB+NIAuGDBUADcjM3FE8jBgKFZwLFp6B2dXDwY-HiQ0XJZ2Dkw5VFzdAyNBXIaXNy8fFq4AbwkYRTwCNoJBecWVVB4+03EAXyA

asked 2 days ago

Correct Answer

No, this is not how infer should be used. If you want TypeScript to infer the return type of the function, just don't specify a return type.

function stateCallback(name: string, age: number) {
  setName(name)
  setAge(age);
}
// return type of stateCallback is inferred as void

The infer keyword can be used (among other things) to extract information from a type. So if you pass a function type to CallbackType, it will return the function's return type.

type CallbackType<T> = T extends () => infer R ? R : never

type Result = CallbackType<() => string>
// -> string
answered 2 days ago