microsoft / microsoft/TypeScript

Type Assertion for Function Parameters

Open
#62,110 2 comments 1 reaction 0 assignees View on GitHub
Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

Research direction

No files, tests, or compiler entry points are named in the issue. Start by examining the proposed parameter-assertion syntax and its interaction with callback assignability, then define the type-checking behavior and tests needed to show the examples work without changing emitted JavaScript.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.