Microsoft/TypeScript

TypeScript can't infer type of default parameters

Open

#59.643 geöffnet am 15. Aug. 2024

Auf GitHub ansehen
 (2 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)TypeScript (6.726 Forks)batch import
Domain: check: Type InferenceHelp WantedPossible Improvement

Repository-Metriken

Stars
 (48.455 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 6T 17h) (9 gemergte PRs in 30 T)

Beschreibung

🔎 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 Generator type is not generic)

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/CYUwxgNghgTiAEAzArgOzAFwJYHtVNQBEQYsA3EAHgEF4QAPDEVYAZ3jQGtUcB3VANoBdADTwASgD4AFACh4CggC540gHQbYAc1YrqASngBeSfADizElAw4YlLj35ipI2fpUO++APQAqX-AAtjhgnCDA8HAYyDD4vt4A3LKyiEQk5CDSKOjYePC+0lDG8AAMYgBGxQDkVYYA3vLwYHisOBAgahA4WtINivBQrvDe3vAAegD8jQrl8iPjUwoAvvpJK0lAA

💻 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