microsoft / microsoft/TypeScript
Allow this in type guards when type of this is explicitly specified in method signature
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.4k
- Merge medio
- 1 d 19 h
- PR fusionados (30 d)
- 117
Descripción
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.
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza reproduciendo el error 2526 con los ejemplos de guard para literales de objeto en TypeScript Playground y, después, sigue el flujo de comprobación de tipos para una firma de método explícita this: SomeType y su condición de guard. Se considera completado cuando el diagnóstico se elimina para este caso, ambos ejemplos pasan la comprobación de tipos tal como se muestran y el comportamiento existente para el uso no válido de this permanece sin cambios.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- typescript
- Área
- compilers
- Tipo de issue
- Nueva funcionalidad
- Dificultad
- 3/5
- Tiempo estimado
- 1-2 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 35/100