-
Notifications
You must be signed in to change notification settings - Fork 10
/
never.ts
82 lines (66 loc) · 1.58 KB
/
never.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
function error(): never {
throw new Error('never returns');
}
function neverDone(): never {
while(true) {
}
}
// without never
function error() {
throw new Error('any error');
}
let possiblyNull: string | null = '' as any;
if(!possiblyNull) error();
possiblyNull;
// ^? let possiblyNull: string | null
// with never
function error(): never {
throw new Error('any error');
}
let possiblyNull: string | null = '' as any;
if(!possiblyNull) error();
possiblyNull;
// ^? let possiblyNull: string
// or
const nonNull = possiblyNull ?? error();
function unknownLanguages(lang: never): never {
throw new Error(`${lang} not known`);
}
type Languages = 'js' | 'ts';
function getRealName(language: Languages): string {
switch(language) {
case 'js':
return 'JavaScript';
case 'ts':
return 'TypeScript';
default:
return unknownLanguages(language);
}
}
type ImageMessage = {
imgPath: string;
text?: never;
}
type TextMessage = {
text: string;
imgPath?: never;
}
type Message = {timestamp: number, sender: string} & (ImageMessage | TextMessage);
const m: Message = {
imgPath: '/path/img',
sender: 'Christian Worz',
text: 'A text',
timestamp: 123
}
type Filter<Obj extends Object, ValueType> = {
[Key in keyof Obj
as ValueType extends Obj[Key] ? Key : never]
: Obj[Key]
}
type IsNever<T> = T extends never ? true : false;
type R = IsNever<never>;
// ^? never => never is an empty union type so nothing to check for to extend. so its never again
// Fix:
type IsNever<T> = [T] extends [never] ? true : false;
type R = IsNever<never>;
// ^?