Microsoft/TypeScript

`ReturnType` and `InstanceType` don't work for functions/constructors with `never` in their parameters

Open

#55.667 aperta il 7 set 2023

Vedi su GitHub
 (3 commenti) (6 reazioni) (0 assegnatari)TypeScript (6726 fork)batch import
Domain: lib.d.tsEffort: CasualExperimentation NeededHelp WantedSuggestion

Metriche repository

Star
 (48.455 star)
Metriche merge PR
 (Merge medio 6g 17h) (9 PR mergiate in 30 g)

Descrizione

🔎 Search Terms

ReturnType InstanceType any never

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about ReturnType and InstanceType.

⏯ Playground Link

https://www.typescriptlang.org/play#code/C4TwDgpgBA+gjFAvFAShYBXATgOwCrgQA8AFAHQUCGWA5gM4BcUOEAbhFgJRIB8UA5ADMA9sP48AUAHopUOQD0A-BImhIsAExIoASRx1glHAGMIBSERYB3KOSq1GzNh26I+Q0eOmyFioA

💻 Code

type _1 = ReturnType<(...args: never) => 'foo'>
//   ^? type _1 = any

type _2 = InstanceType<new (...args: never) => 'foo'>
//   ^? type _2 = any

🙁 Actual behavior

ReturnType and InstanceType always evaluate to any when given a function/constructor whose parameters are ...args: never (or ...args: never[], a: never, b: string, etc).

🙂 Expected behavior

ReturnType and InstanceType should return the actual return/instance type.

Additional information about the issue

Changing the parameter constraint in the conditions of these types from any to never seems to fix the issue:

type ReturnType<T extends (...args: any) => any> = T extends (...args: never) => infer R ? R : any

type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: never) => infer R ? R : any

I don't think this will cause any regressions, and did some spot-checking to validate that, but haven't run the entire test suite or anything like that yet.

Guida contributor