Microsoft/TypeScript
GitHub ã§èŠãTypeScript can't infer type of default parameters
Open
#59,643 opened on 2024幎8æ15æ¥
Domain: check: Type InferenceHelp WantedPossible Improvement
Repository metrics
- Stars
- Â (48,455 stars)
- PR merge metrics
-  (å¹³åããŒãž 6d 17h) (30d ã§ 9 merged PRs)
説æ
ð 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
// ^?
});
});