-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path104.tsx
127 lines (80 loc) · 2.33 KB
/
104.tsx
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// # Generics
// ---
// SLIDE
// ---
// ## Syntax
function genericFunction<T>(arg: T): T {
return arg;
};
_number = genericFunction<number>(1);
class GenericClass<T> {
arg: T;
constructor(arg: T) {
this.arg = arg
}
};
let _numberObject = new GenericClass<number>(_number);
interface GenericInterface<T> { arg: T };
let _numberObjectAsInterface: GenericInterface<number> = _numberObject;
type GenericType<T> = { arg: T };
let _numberObjectAsType: GenericType<number> = _numberObject;
// ---
// SLIDE
// ---
// ## Generic Constraints
function deepCopyObject<T extends object>(obj: T): T {
return JSON.parse(JSON.stringify(obj));
}
let _numberObjectCopy = deepCopyObject(_numberObject);
// let _numberObjectCopy: GenericClass<number>
// let _numberCopy = deepCopyObject(_number)
// result: Argument of type 'number' is not assignable to parameter of type 'object'.ts(2345)
// ---
// SLIDE
// ---
// ## How to type a class?
function createObject<T extends object, CArgs extends any[]>(
_class: new (...args: CArgs) => T,
_args: CArgs
): T {
return new _class(..._args);
}
let _numberObject2 = createObject(GenericClass, [1]);
// let _numberObject2: GenericClass<number>
// ---
// SLIDE
// ---
// ## Default values & React usage
import * as React from 'react';
interface DropdownProps<T extends string | number> {
defaultValue?: T;
options: T[];
onChange: (value: T) => void;
}
class Dropdown<T extends string | number = string> extends React.Component<DropdownProps<T>> {
// implementation
}
let Element = ({ opts1, opts2 }: { opts1: string[], opts2: number[] }) => {
const _onChange1 = React.useCallback((val: string) => console.log(val), []);
// const _onChange1: (val: string) => void
const _onChange2 = React.useCallback<DropdownProps<number>['onChange']>(
(val: number) => console.log(val),
[]
);
// const _onChange2: (value: number) => void
return (
<>
<Dropdown options={opts1} onChange={_onChange1} />
<Dropdown<number> options={opts2} onChange={_onChange2} />
<Dropdown options={opts2} onChange={_onChange2} defaultValue={1} />
</>
)
}
// ---
// NEXT
// ---
// ## FORMAT FIX: the _ is not working in tsx
_numberObjectAsInterface
_numberObjectAsType
_numberObjectCopy
_numberObject2