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>{

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


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) {
// 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