-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerics-example.ts
More file actions
44 lines (38 loc) · 949 Bytes
/
generics-example.ts
File metadata and controls
44 lines (38 loc) · 949 Bytes
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
class Dictionary<T> {
private _dict: { [key: string]: T } = {};
public getValueByKey(key: string): T | null {
if (this._dict[key]) {
return this._dict[key];
}
else {
return null;
}
}
public setValue(key: string, value: T): void {
if (this._dict[key]) {
throw new Error("Key already exists");
}
else {
this._dict[key] = value;
}
}
public deleteValue(key: string): void {
if (this._dict[key]) {
// this._dict[key] = undefined;
delete this._dict[key];
}
else {
throw new Error("Key does not exist");
}
}
}
const d: Dictionary<string> = new Dictionary();
try {
d.setValue("Hello", "Hello");
d.setValue("World", "World");
d.deleteValue("Hello");
console.log("End of execution");
}
catch (error) {
console.error(error);
}