microsoft / microsoft/TypeScript
Type Assertion for Function Parameters
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.3k
- Merge medio
- 2 d 4 h
- PR fusionados (30 d)
- 132
Descripción
### 🔍 Search Terms
"function parameter", "type assertion"
### ✅ Viability Checklist
- [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
- [x] This wouldn't change the runtime behavior of existing JavaScript code
- [x] This could be implemented without emitting different JS based on the types of the expressions
- [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- [x] This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- [x] This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
### ⭐ Suggestion
I don't know whether some one had proposed this, but at least I have not found any in my searches.
A simple new syntax like this:
```
function(e: Type as AssertType) {
}
(e: Type as AssertType) => {
}
```
### 📃 Motivating Example
Let's take `Event` and `CustomEvent` as an example.
Now we have a class inheriting from EventTarget, for we want to expose an interface to the external.
```typescript
class MyClass extends EventTarget {
constructor() {
super();
// do stuff
}
}
```
We have a custom event type `valueChange`, and we want it only be dispatched with `CustomEvent`. So we wrap `ValueChangeEvent` into a class, and make sure nowhere else we use `new CustomEvent("valueChange", {details})`.
```typescript
class ValueChangeEvent extends CustomEvent {
constructor(detail: string) {
super("valueChange", { detail });
}
}
class MyClass extends EventTarget {
constructor() {
super();
// do stuff
}
}
```
And now we know `e` can only be of type `ValueChangeEvent`, but TypeScript doesn't know that and so it will complain that `ValueChangeEvent` is not assignable to type `Event`, for the latter is larger than the former.
```typescript
const obj = new MyClass();
obj.addEventListener("valueChange", (e: ValueChangeEvent) => {
// do stuff
})
```
We currently have some way to solve this.
The first is checking the type of `e` first. It is troubling to do this in this scenario, but in some stricter situations it might be the best way to go.
```typescript
obj.addEventListener("valueChange", (e: Event) => {
if (!(e instanceof ValueChangeEvent)) {
return;
}
// And we can use `e` as a `ValueChangeEvent` fair and square.
});
```
The second is to reassign an variable and use type assertion to tell TypeScript that we know what we are doing.
```typescript
obj.addEventListener("valueChange", (e: Event) => {
const valueChangeEvent = e as ValueChangeEvent;
});
```
But this is not very elegant, and generates a unnecessary and awkward extra line in the final JavaScript code.
Another way is to use the `as` keyword each time we need to access `detail` of the event object. If we assign `detail` to a variable, we can use it without the `as` keyword.
```typescript
obj.addEventListener("valueChange", (e: Event) => {
const detail = (e as CustomEvent).detail;
});
```
It is not so troublesome in the `CustomEvent` example, but if we have more than one extra properties in the type we are sure it would be, we need to assign them to more variables. Nevertheless, we can use destructuring to assign them to variables, so that we still only use `as` once.
```typescript
type Type = ...;
type MyType = {
extra1: string;
extra2: number;
extra3: boolean;
...
} & Type;
const fnReceivingCallback = (callback: (param: Type) => void) => {
// internal logic
}
// param is guaranteed to be MyType by the developer
fnReceivingCallback((param: Type) => {
const {extra1, extra2, extra3} = param as MyType;
})
```
And the last way is to assert the type of the function. To be honest, it is the worst approach among these four.
```typescript
obj.addEventListener("valueChange", (e: ValueChangeEvent)) => {
} as (e: Event) => boolean);
```
But personally, I think it is the most elegant that we use type assertions in the parameter list, like this. In this way, TypeScript will know that we have ensured that the parameter is of type `ValueChangeEvent`.
```typescript
obj.addEventListener("valueChange", (e as ValueChangeEvent) => {
});
```
### 💻 Use Cases
1. What do you want to use this for?
2. What shortcomings exist with current approaches?
3. What workarounds are you using in the meantime?
All shown in the column above.
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
En el issue no se indican archivos, pruebas ni puntos de entrada del compilador. Empieza examinando la sintaxis propuesta para las aserciones de parámetros y su interacción con la asignabilidad de los callbacks; después, define el comportamiento de la comprobación de tipos y las pruebas necesarias para demostrar que los ejemplos funcionan sin cambiar el JavaScript emitido.
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
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 25/100