简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM