Home > Software design >  how to use infer to infer the return type of a void function?
how to use infer to infer the return type of a void function?

Time:09-23

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

CodePudding user response:

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
  • Related