Skip to content

Commit c17280d

Browse files
authored
Update never.md
1 parent 4559c01 commit c17280d

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

docs/types/never.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,50 @@ As soon as someone tells you that `never` is returned when a function never exit
5757

5858
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`.
5959

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+
throw new Error(message);
68+
}
69+
70+
// Inferred return type: never
71+
const failExpression = function(message: string) {
72+
throw new Error(message);
73+
};
74+
```
75+
76+
Ofcourse you can fix it by an explict annotation:
77+
78+
```ts
79+
function failDeclaration(message: string): never {
80+
throw new Error(message);
81+
}
82+
```
83+
84+
Key reason is backword compatability with real world JavaScript code:
85+
86+
```ts
87+
class Base {
88+
overrideMe() {
89+
throw new Error("You forgot to override me!");
90+
}
91+
}
92+
93+
class Derived extends Base {
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.
103+
60104
<!--
61105
PR: https://github.com/Microsoft/TypeScript/pull/8652
62106
Issue : https://github.com/Microsoft/TypeScript/issues/3076

0 commit comments

Comments
 (0)