microsoft / microsoft/TypeScript
Cannot assign to ... because it is a read-only property when using type guard in ctor
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
A common pattern is declaring narrower types for members in derived classes. However, when combined with type guards, assignement to readonly members fails with an unexpected "Cannot assign to ... because it is a read-only property" error.
TypeScript Version: 3.7.2
Search Terms:
class member read-only property type narrowing covariant type guard
Code
class Foo {
public readonly x: string | number;
constructor() {
if (isBar(this))
// error TS2540: Cannot assign to 'x' because it is a read-only property.
this.x = 'string';
else
// no error here
this.x = 123;
}
}
class Bar extends Foo {
// Declare narrower type for member in derived class
public readonly x: string;
}
function isBar(foo: Foo): foo is Bar {
return foo instanceof Bar;
}
Expected behavior:
Assignment to this.x should be allowed with or without type guard in the constructor
Actual behavior:
error TS2540: Cannot assign to 'x' because it is a read-only property.
Playground Link:
Related Issues:
It is as if the type guard creates an invisible alias (cf https://github.com/microsoft/TypeScript/issues/14241), and asignment inside the type guard fails.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the TypeScript 3.7.2 example in the linked Playground and compare the guarded and unguarded assignments. Trace the compiler's type-guard and readonly-property checks, then add a regression test for the example. Done means both constructor assignments are accepted without producing TS2540.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100