File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * public / private / protected
3+ * getter / setter
4+ */
5+
6+ ( function ( ) {
7+
8+ class A {
9+ protected num : number ;
10+ // 语法糖,在构造函数中定义属性,public age: number
11+ constructor ( num : number , public age : number ) {
12+ this . num = num ;
13+ this . age = age ;
14+ }
15+ }
16+ class B extends A {
17+ test ( ) {
18+ console . log ( this . num ) ;
19+ }
20+ }
21+ const b = new B ( 777 , 18 ) ;
22+ // b.num = 1;
23+
24+
25+ class Person {
26+ // 默认 public
27+ public age : number = 30 ;
28+ public readonly name : string = 'csxiaoyao' ;
29+ private _hobby : Array < string > ;
30+
31+ constructor ( age : number ) {
32+ this . age = age ;
33+ this . _hobby = [ ] ;
34+ }
35+
36+ // getter / setter
37+ /*
38+ getHobby() {
39+ return this._hobby;
40+ }
41+ setHobby(hobby: Array<string>) {
42+ this._hobby = hobby;
43+ }
44+ */
45+ get hobby ( ) {
46+ return this . _hobby ;
47+ }
48+ set hobby ( hobby : Array < string > ) {
49+ this . _hobby = hobby ;
50+ }
51+ }
52+
53+ const per = new Person ( 18 ) ;
54+ // getter
55+ console . log ( per . hobby ) ;
56+
57+
58+ } ) ( ) ;
Original file line number Diff line number Diff line change 1+
2+ /**
3+ * 定义函数或类时,不明确的类型可以使用泛型,在执行时确定类型
4+ * fn<T> 定义泛型T
5+ */
6+ function fn < T > ( a : T ) : T {
7+ return a ;
8+ }
9+ // 泛型自动推断
10+ fn ( 10 ) ;
11+ // 指定泛型
12+ fn < string > ( 'hello' ) ;
13+
14+ // 定义多个泛型
15+ function fn2 < T , K > ( a : T , b : K ) : T {
16+ console . log ( b ) ;
17+ return a ;
18+ }
19+ fn2 < number , string > ( 123 , 'hello' ) ;
20+
21+ // 限制泛型范围
22+ interface Inter {
23+ length : number ;
24+ }
25+ function fn3 < T extends Inter > ( a : T ) : number {
26+ return a . length ;
27+ }
28+ fn3 ( { length :10 } ) ;
29+
30+ // class
31+ class MyClass < T > {
32+ name : T ;
33+ constructor ( name : T ) {
34+ this . name = name ;
35+ }
36+ }
37+ const mc = new MyClass < string > ( 'csxiaoyao' ) ;
Original file line number Diff line number Diff line change 66 < title > TS-OOP</ title >
77</ head >
88< body >
9- < script src ="dist/02-abstract .js "> </ script >
9+ < script src ="dist/05-泛型 .js "> </ script >
1010</ body >
1111</ html >
You can’t perform that action at this time.
0 commit comments