简体   繁体   中英

Why is the generic type parameter T “unknown” in the return type? How can I type this function so that the return type is correctly inferred?

The typescript handbook ( https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints ) says this about Generic Constraints:

You can declare a type parameter that is constrained by another type parameter.

In this contrived example, how can I get "T" in in the return type of wrap() to be correctly inferred?


function wrap<T, F extends (() => T)>(cb: F): [T, F] {
  return [cb(), cb]
}

function load(): string {
  return ''
}

const [
  value, // unknown, should be string. Can I get typescript to infer this?
  wrapped, // () => string
] = wrap(load)

Typescript has problems inferring T from a construct like this func<T, F extends (() => T)> . In that case, it is usually better to rely on infer . For your example, we can use the utility type ReturnType , which uses infer internally and does exactly what we need:

function wrap<F extends (() => any)>(cb: F): [ReturnType<F>, F] {
  return [cb(), cb]
}

function load(): string {
  return ''
}

const [
  value, // string
  wrapped, // () => string
] = wrap(load)

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