microsoft / microsoft/TypeScript
Covariant assignability of type guard functions is unsound
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.4k
- Merge medio
- 1g 19h
- PR unite (30g)
- 117
Descrizione
TypeScript Version: master (af8e44a)
Search Terms: user-defined type guard predicate assignable assignability unsound covariant invariant
Code
class A {
a: string;
}
class B extends A {
b: string;
}
function isB(x: {}): x is B {
return x instanceof B;
}
const isA: (x: {}) => x is A = isB; // allowed, should be compile error
const x = <A | string>new A();
if (!isA(x)) {
console.log(x.slice()); // runtime error
}
Expected behavior: Assignability error where marked.
Actual behavior: Successful compilation, runtime error.
Playground Link: link
Related Issues: #24865
If we want a kind of type guard function that is covariant, we need to not narrow when it returns false, i.e., a "true" result would be sufficient but not necessary for the value to be of the tested type. And we'd need a different syntax for the type of a type guard function that is necessary and sufficient compared to a type guard function that is sufficient but not necessary. One idea for the latter is (x: {}) => x is A | false. (A type guard function that is necessary but not sufficient would then be (x: {}) => x is A | true.) Getting all these variants supported would help us support conjunctions and disjunctions of type guard calls with other boolean expressions in #24865. If you like, this issue can be for the removal of the unsound assignability rule and I can file a separate suggestion for the new kinds of type guard functions.
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 con la riproduzione collegata in Playground e con l’assegnazione indicata di isB al tipo isA. Traccia il modo in cui il compilatore verifica l’assegnabilità delle funzioni predicato di tipo, usando la issue correlata come contesto. Il lavoro è concluso quando l’assegnazione produce un errore e viene impedito il narrowing non sicuro dimostrato.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- typescript
- Ambito
- compilers
- Tipo di issue
- Bug
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 30/100