Description
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: -