Skip to content

Generate 'get' and 'set' accessors refactoring with optional property causes compiler error #40994

Closed
@gabritto

Description

@gabritto

TypeScript Version: 4.0.2

Search Terms: generate get, optional property, generate accessors

Code
Before:

class Class {
    [| optionalField?: string; |]
}

Apply "Generate 'get' and 'set' accessors" refactoring to [| selected range |].
After:

class Class {
    private _optionalField?: string;
    public get optionalField(): string {
        return this._optionalField;
    }
    public set optionalField(value: string) {
        this._optionalField = value;
    }
}

Actual behavior:
Compiling with strictNullChecks: true gives error TS2322: Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.
Error happens because the getter generated has return type string but returns _optionalField, and _optionalField's type is actually string | undefined because it is optional, which is not assignable to type string.

Expected behavior:
No type checking errors. Maybe the getter and setter functions should actually have type string | undefined instead of string?

Playground Link: code before refactoring, code after refactoring
Related Issues: -

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: Refactoringse.g. extract to constant or function, rename symbolEffort: ModerateRequires experience with the TypeScript codebase, but feasible. Harder than "Effort: Casual".Help WantedYou can do this

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions