microsoft / microsoft/TypeScript

Type Assertion for Function Parameters

Aperta
#62,110 2 commenti 1 reazione 0 assegnatari Vedi su GitHub
Awaiting More Feedback Suggestion
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
2g 4h
PR unite (30g)
132

Descrizione

### 🔍 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.

Guida per i contributori

Apri la guida per i contributori

Direzione di ricerca

Nell'issue non sono indicati file, test o punti di ingresso del compilatore. Inizia esaminando la sintassi proposta per le asserzioni dei parametri e la sua interazione con l'assegnabilità dei callback, quindi definisci il comportamento del controllo dei tipi e i test necessari per dimostrare che gli esempi funzionano senza modificare il JavaScript emesso.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
typescript
Ambito
compilers
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.