forked from wesbos/hot-tips
-
Notifications
You must be signed in to change notification settings - Fork 0
/
typescript-satisfies.ts
100 lines (78 loc) · 1.91 KB
/
typescript-satisfies.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/* eslint-disable */
type Setting = string | number | { [key: string]: Setting } | Setting[];
type Settings = Record<string, Setting>;
function getData() {
return { data: 'good' };
}
const mySettings = {
title: `Wes' Website`,
data: getData(),
size: 200,
overrides: [
{ 'font-size': '20px' },
],
styleConfig: {
color: 'red',
},
} satisfies Settings;
mySettings.overrides.at(0)?.['font-size'];
// Valid Properties
mySettings.title = 'New title';
console.log(mySettings.size);
// Invalid Properties
console.log(mySettings.scott);
mySettings.limt = 200;
mySettings.size.toLocaleString();
mySettings.overrides.at(0)?.['font-size'];
console.log(metaData.title);
console.log(metaData.doesntExist);
type DictionaryMap = Map<string, string | number>;
type DictionaryRecord = Record<string, string | number>;
type DictionaryObject = { [key: string]: string | number };
/* prettier-disable */
const dictionaryObject = {
welcome: 'Welcome to My Website!',
buy: 'Buy it now!',
price: 100,
} satisfies DictionaryObject;
const dictionaryObjectConst = {
welcome: 'Welcome to My Website!',
buy: 'Buy it now!',
price: 100,
} as const;
dictionaryObject.nope;
// satisfies can be Updated
dictionaryObject.welcome = 'Welcome to My Website!';
// const cant
dictionaryObjectConst.welcome = 'Welcome to My Website!';
dictionaryObject.newVal = 'Welcome to My Website!';
const dictionaryMap = new Map([
[
'welcome',
'Welcome to My Website!',
],
[
'buy',
'Buy it now!',
],
]) satisfies DictionaryMap;
dictionaryMap.get('welcome');
// Narrowing
type User = {
id: string | number;
};
const wes: User = {
id: 'wesbos',
};
console.log(wes.id.toUpperCase());
console.log(wes.id.toFixed());
wes.id = 200;
wes.id = 'Cool';
function logUser(user: User satisfies { id: string }) {
user.id
}
if (typeof wes.id === 'string') {
console.log(wes.id.toUpperCase());
} else {
console.log(wes.id.toFixed());
}