Description
Search Terms
generic declaration return type parameter
Suggestion
Today you can write declarations like this:
function getThing<T>(): T {
return null as any as T; // ¯\_(ツ)_/¯
}
const x = getThing<"cool">(); // Type safety!
This isn't particularly meaningful - getThing
has no plausible correct implementation that doesn't rely on the caller asking for the correct type by coincidence.
We then also started allowing this to enable some other scenarios (#16072):
// This will return a number because I wished for it
const p: number = getThing();
See also #5256 (comment)
The rule should be: All type parameters must appear in an input position; this would need to be under some flag like --strictTypeParameterDeclarations
(please bikeshed).
Users should return any
or unknown
instead in these cases.
A lint rule approximating this can be done syntactically so we should scan DefinitelyTyped to see what the breakage would look like.
Use Cases
Mostly to allow us to clean up DefinitelyTyped.
Examples
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript / JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. new expression-level syntax)