You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/types/never.md
+44Lines changed: 44 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -57,6 +57,50 @@ As soon as someone tells you that `never` is returned when a function never exit
57
57
58
58
A function that *returns* nothing returns a Unit `void`. However, a function *that never returns* (or always throws) returns `never`. `void` is something that can be assigned (without `strictNullChecking`) but `never` can *never* be assigned to anything other than `never`.
59
59
60
+
# Type inference in never returning functions
61
+
62
+
For function declarations TypeScript infers `void` by default as shown below:
63
+
64
+
```ts
65
+
// Inferred return type: void
66
+
function failDeclaration(message:string) {
67
+
thrownewError(message);
68
+
}
69
+
70
+
// Inferred return type: never
71
+
const failExpression =function(message:string) {
72
+
thrownewError(message);
73
+
};
74
+
```
75
+
76
+
Ofcourse you can fix it by an explict annotation:
77
+
78
+
```ts
79
+
function failDeclaration(message:string):never {
80
+
thrownewError(message);
81
+
}
82
+
```
83
+
84
+
Key reason is backword compatability with real world JavaScript code:
85
+
86
+
```ts
87
+
classBase {
88
+
overrideMe() {
89
+
thrownewError("You forgot to override me!");
90
+
}
91
+
}
92
+
93
+
classDerivedextendsBase {
94
+
overrideMe() {
95
+
// Code that actually returns here
96
+
}
97
+
}
98
+
```
99
+
100
+
If `Base.overrideMe` .
101
+
102
+
> Real world TypeScript can overcome this with `abstract` functions but this inferrence is maintained for compatability.
0 commit comments