Microsoft/TypeScript

Ambient type for constructor parameter property with default does not include 'undefined' when the parameter is followed by one without a default

Open

#48.547 geöffnet am 4. Apr. 2022

Auf GitHub ansehen
 (2 Kommentare) (1 Reaktion) (0 zugewiesene Personen)TypeScript (6.726 Forks)batch import
BugDomain: Declaration EmitHelp Wanted

Repository-Metriken

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

Beschreibung

Bug Report

🔎 Search Terms

constructor parameter property default undefined

🕗 Version & Regression Information

This is the behaviour in every version in the Playground (3.3 through to 4.6.2)

⏯ Playground Link

Playground link with relevant code

💻 Code

class C { constructor(public a = 123, b: string) {} }

🙁 Actual behavior

.d.ts emit:

declare class C {
    a: number;
    constructor(a: number, b: string);
}

🙂 Expected behavior

Parameter a should be of type number | undefined. Otherwise, it's impossible to initialise the field to its default.

Note that if parameter b is removed, given a default, or made optional, a is then correctly emitted as optional (a?: number). Clearly TypeScript won't emit an optional followed by a required parameter, but it also doesn't add the undefined type.

If a is not a property (remove public) the emitted signature correctly includes undefined.

Secondary bug: undefined is also missing from the type hint for a. However, the compiler correctly accepts undefined when the class is declared inline:

That differs from the behaviour when only the .d.ts definition is available, where the compiler then rejects undefined in the same position.

Contributor Guide