-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclasses.tsx
142 lines (120 loc) · 4.42 KB
/
classes.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// Классы вводит ES6, TS лишь добавляет типизацию
// ------------------ Уровни доступа --------------------------
// public - доступен вне класса, уровень доступа 100
// private - недоступен вне класса, уровень доступа 1
// protected - доступен только для наследых классов, уровень 0
// ------------------------------------------------------------
// Old constructor example
function OldConstructor(fieldVal) {
this.field = fieldVal || 123;
}
OldConstructor.prototype.method = function() {
return this.field;
}
const instance = new OldConstructor(1);
instance.method(); // -> 1
// New class example
// Типизация класса не отличается от интерфейса
class Constructor { // можем также декларировать поля
field1: number = 123; // с предопределенным типов
field2 = 123; // или без
[n: number]: number; // использовать индекс-сигнатуру
readonly fiel: number; // использовать readonly
someField ? = 123; // использовать optional type
public field = 123; // использовать публичность переменных
private privateField = 123;
public constructor(arg: number) {
this.field = arg;
}
// использовать публичность методов
public publicMethod() {
return this.field;
}
protected protecedMethod() {
return this.field + this.privateMethod();
}
private privateMethod() {
return this.field + this.protecedMethod();
}
}
const myInstance = new Constructor(123);
// myInstance.privateField; // недоступно
// myInstance.privateMethod(); // недоступно
// Дочерний класс
class Child extends Constructor {
public childMethod() {
this.publicMethod();
this.protecedMethod();
// this.privateMethod(); // недоступен для дочерних классов
}
// Сохранение уровня доступа
protected protecedMethod() {
return super.protecedMethod();
}
// Можно повышать уровень доступа
// protected privateMethod() {...} // 0->1
// public protecedMethod() {...} // 1->100
// public privateMethod() {...} // 0->100
// Но нельзя понижать уровень доступа
// protected publicMethod() {...} // 100->1
// private protecedMethod() {...} // 1->0
// private publicMethod() {...} // 100->0
}
// Абстрактные классы -------------------------------------
// (нужны только для наследования)
abstract class AbstractClass {
// абстрактные переменные и методы
public abstract abstractField: number;
public abstract abstractMethod(): number;
// обычные переменные и методы
protected protectedMethod() {
return this.abstractField;
}
}
// const instance2 = new AbstractClass(); // ошибка
class NewChild extends AbstractClass {
// Implement inherited abstract classes - "Ctrl + ."
public abstractField: number = 123;
public abstractMethod(): number {
return 0;
}
}
// Implement interfaces -----------------------------------
// (работаем также как и с абстрактными классами, только без реализации)
interface MyInterface1 {
field: string;
method(): string;
}
class NewClass implements MyInterface1 {
field: string;
method(): string {
throw new Error("Method not implemented.");
}
}
// Generic interface & class ------------------------------
interface MyInterfaceG<T> {
field: string;
method(): string;
}
class NewClassG<T> implements MyInterfaceG<T> {
field: string;
public conf?: T;
method(): string {
throw new Error("Method not implemented.");
}
}
// Class component ----------------------------------------
import * as React from "react";
class MyComponent extends React.Component<{prop1: number}, {state1: string}> {
constructor(props) {
super(props);
this.state = {
state1: '123'
}
}
public render() {
return (
<div>{this.props.prop1}</div>
)
}
}