microsoft / microsoft/TypeScript
TypeScript can't infer type of default parameters
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.4k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
🔎 Search Terms
infer default parameters
function wrapper
function factory
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ
- I tried down to version 4.0.3 (since in the earlier version
Generatortype is not generic)
- I tried down to version 4.0.3 (since in the earlier version
⏯ Playground Link
💻 Code
declare function fnDerive<A extends unknown[], R>(
fn: (...args: A) => Generator<unknown, R>,
): unknown /** mocked return */;
fnDerive(function *(a = 0, b = '') {
console.log({
a,
// ^?
b
// ^?
});
});
🙁 Actual behavior
The type of a and b is unknown.
🙂 Expected behavior
The type of a and b should be number and string
Additional information about the issue
I was working with a library gensync when I hit this issue, and I extracted the minimum reproduction out of it.
Note that if I don't use default parameters, typescript can infer the a and b types correctly:
declare function fnDerive<A extends unknown[], R>(
fn: (...args: A) => Generator<unknown, R>,
): unknown /** mocked return */;
fnDerive(function *(a?: number | undefined, b?: string | undefined) {
console.log({
a,
// ^?
b
// ^?
});
a ??= 0;
b ??= '';
console.log({
a,
// ^?
b
// ^?
});
});
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked TypeScript Playground and the minimal fnDerive reproduction, then trace how default parameters are handled during generic function inference. Done means the example infers a as number and b as string, while the equivalent explicitly optional-parameter example continues to behave correctly.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100