microsoft / microsoft/TypeScript
Allow this in type guards when type of this is explicitly specified in method signature
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 2g 4h
- PR unite (30g)
- 132
Descrizione
Search Terms
"A 'this' type is available only in a non-static member of a class or interface.(2526)" guard
Relevant: #37796 (but this one is different)
Suggestion
Remove error 2526 in guard condition if type of this is specified explicitly using this: SomeType.
Since both guard condition and method body work as expected, I assume only the error check needs to be removed.
Use Cases
Defining a guard without having a class (have some cases where full class would be an overkill).
Examples
({
guard(this: { x?: 1 }): this is { x: 1 } {
return this.x === 1;
}
})
Note that this is not any and works perfectly fine in both the method body and the guard:
const o = ({
x: 1 as 1|2,
guard(this: { x: 1 | 2 }): this is { x: 1 } {
// body works
return this.x === 1;
}
});
if (o.guard()) {
// guard works
const check: 1 = o.x;
}
Would be good to support guard in ThisType<> as well (see #37796), but can be a separate thing.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
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’errore 2526 con gli esempi di guard per i literal di oggetto in TypeScript Playground, quindi traccia il percorso del controllo dei tipi per una firma di metodo esplicita this: SomeType e la relativa condizione di guard. Il lavoro è completato quando la diagnostica viene rimossa per questo caso, entrambi gli esempi superano il controllo dei tipi come mostrato e il comportamento esistente per l’uso non valido di this rimane invariato.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- typescript
- Ambito
- compilers
- Tipo di issue
- Funzionalità
- Difficoltà
- 3/5
- Tempo stimato
- 1-2 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100