microsoft / microsoft/TypeScript
ES6 Class: `asserts this is Type` raises error when variable containing instance is type narrowed
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
Bug Report
🔎 Search Terms
- Error: "Assertions require every name in the call target to be declared with an explicit type annotation"
- Assertation function as class method
- Type narrowing class and then calling assertation method
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about this
⏯ Playground Link
Playground link with relevant code
💻 Code
class MyClass {
public assertIsMyClass(): asserts this is MyClass {
if (!(this instanceof MyClass)) {
throw new Error('this was not of type MyClass');
}
}
}
const maybeMyClass: MyClass | undefined = new MyClass();
if (maybeMyClass) {
// This fails with error:
// Assertions require every name in the call target to be declared with an explicit type annotation.(2775)
maybeMyClass.assertIsMyClass();
// But if we simply assign to a new variable without the optionality, it's fine:
// this line works because we have narrowed the type through the if statement above
const definitelyMyClass: MyClass = maybeMyClass;
// This raises no error even though it's equivalent to the first attempt
definitelyMyClass.assertIsMyClass();
}
🙁 Actual behavior
Calling the class method assertation function raises error: "Assertions require every name in the call target to be declared with an explicit type annotation.(2775)"
🙂 Expected behavior
It should pass validation and narrow to the type given in the assertation.
This is because it will have this behavior if you simply assign to a new variable with a new type annotation (but which is equivalent to the narrowed type at that point).
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 con el enlace de Playground proporcionado y reproduce el diagnóstico del ejemplo de código, comparando la variable cuyo tipo se ha estrechado con la variable anotada explícitamente. Traza la validación de las llamadas de aserción en el compilador de TypeScript y añade cobertura para este caso de método de clase. La tarea estará terminada cuando la llamada con el tipo estrechado supere la validación y las comprobaciones de aserción existentes sigan siendo correctas.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- typescript
- Área
- compilers
- Tipo de issue
- Error
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 35/100