microsoft / microsoft/TypeScript
Cannot assign to ... because it is a read-only property when using type guard in ctor
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 1g 19h
- PR unite (30g)
- 117
Descrizione
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.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia riproducendo l'esempio TypeScript 3.7.2 nel Playground collegato e confronta le assegnazioni protetta e non protetta. Segui i controlli del compilatore per il type guard e le proprietà readonly, quindi aggiungi un test di regressione per l'esempio. Il lavoro è completo quando entrambe le assegnazioni nel costruttore vengono accettate senza produrre TS2540.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- typescript
- Ambito
- compilers
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100