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 创建于 2022年4月4日

在 GitHub 查看
 (2 评论) (1 反应) (0 负责人)TypeScript (6,726 fork)batch import
BugDomain: Declaration EmitHelp Wanted

仓库指标

Star
 (48,455 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 9 个 PR)

描述

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.

贡献者指南