microsoft / microsoft/TypeScript

`asserts this is T` does not narrow type of `this`

Aperta
#60,140 11 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Cursed? Domain: This-Typing Possible Improvement
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
1g 19h
PR unite (30g)
117

Descrizione

🔎 Search Terms
  • asserts this is T
  • narrow
  • assertions
  • I also checked #59707, but it is unrelated (generic types).
🕗 Version & Regression Information
  • Playground: v5.7.0-dev.20241004
  • At least since v5.6.2
⏯ Playground Link

https://www.typescriptlang.org/play/?#code/MYGwhgzhAECC0G8BQ1oHsB2ICeARApgGYCWG+AJgJIawAUAlIiqtMJhGiPgHQhoDmtAESwh9ANzMAvkmaQI+AE4AXOvQBc0eUuUxlAC2IwjcRNBkzZoedABCTVNpVrNT3dAMmT8BOaSXlbAAHfGgAYWgAXlMAHztJJEIAVwxgZWJMLSgdOmBNMI0shRUYYGhvJktk1PTM5XwIZQBGWjzwxmRUYG43NUku7kwcAhIyKhoGcWgAemnoAFFFRTRFTQAFZZCVbGgAciG8IlIKalhd6HI0BugMNGVofAAPI3u64NDdsN3uaA20LcCewOI2O4zOFyuMFu9yeL3QGA87z2tm+-lk1TSGQR9UaACZWvkOnJss5WhJmN1gUcxqdJjM5gB1FYAawgAEI0dAgA

💻 Code
class A {
  onlyDefinedInA() {
    console.log("A");
  }

  assertA(): asserts this is A { }
}


class B {
  assertA(): asserts this is A { }
}

type C = A | B;

function assertA(c: C): asserts c is A {
}

function test1(c: C) {
  c.assertA();
  c.onlyDefinedInA(); // Error: Property 'onlyDefinedInA' does not exist on type 'C'. Property 'onlyDefinedInA' does not exist on type 'B'.
}

function test2(c: C) {
  assertA(c);
  c.onlyDefinedInA(); // Works!
}

Workbench Repro

🙁 Actual behavior

Type of c is not narrowed after the method call, producing an error.

🙂 Expected behavior

I expect the member function to to perform type narrowing.

Additional information about the issue

No response

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con la riproduzione collegata di TypeScript Playground e confronta il caso di chiamata al metodo in test1 con l'asserzione autonoma in test2. Traccia come viene gestito asserts this is A dopo una chiamata a un membro, quindi verifica che la chiamata al metodo restringa c in modo che onlyDefinedInA() venga accettato senza causare regressioni nel caso autonomo.

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à
Tranquilla
Chiarezza
Abbastanza chiara
Idoneità per principianti
48/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.