TypeScript 是 JavaScript 的超集
TypeScript 让人有一种 写JavaScript时 好像在写Java的感觉。
最主要 因工作需要,才来接触 tsc的。
基础
1 | // 字符串新特性, 多行字符串, 模板字符串 |
##面向对象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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171// 面向对象 类 泛型 接口 模块 注解 类型定义文件。
class Person {
public name; // 默认修饰符就是public。
age; //默认就是public修饰符。
private girlFriend; //私有的。 只能类内部访问。
protected father; //类的内部和子类可以访问。
// 构造函数中如果用修饰符指定参数, 则表示先声明一个属性, 然后传参数时赋值,
// 如果没有修饰符, 则是一个局部的变量。
constructor(age: number) {
console.log(`hhhhhhhh`)
this.age = age;
}
// constructor(public age: number) {
// console.log(`hhhhhhhh`)
// }
eat() {
console.log(`${this.name} is eating`)
}
getAge() {
return this.age;
}
private say() {
console.log('私有方法')
}
}
var s1 = new Person(22);
s1.name = 'dottie'
s1.eat()
console.log(s1.getAge())
// 继承
class People {
name: string;
constructor(name: string) {
this.name = name;
}
eat() {
console.log(`i am ${this.name}, eating...`)
}
}
class Employee extends People{
code: number;
constructor(name: string, code: number) {
super(name); //必须要调用父类的构造器
this.code = code;
}
doSomething() {
super.eat();
}
}
var employee = new Employee('dottie', 110);
console.log(employee)
employee.doSomething()
// 泛型
var parr: Array<People> = []; //泛型,只能People类型可以插入
// push unshift 方法返回数组的长度length
console.log(parr.push(new People('dottie')));
console.log(parr.push(new Employee('daejong', 22)));
console.log(parr.unshift(new Employee('xixi', 23)));
console.log(parr.length);
// 接口
interface IPerson {
name: string,
age: number
}
class Person {
constructor(public config: IPerson) {
}
}
var p1 = new Person({
name: 'dottie',
age: 23
})
interface Animal {
eat();
}
class SheetColumn {
name: string;
age: number;
}
class Sheet implements Animal{
constructor(public config: SheetColumn) {
}
eat() {
console.log(`i am eating...`)
}
}
var sheet = new Sheet({
name: 'daejong',
age: 12
})
// 模块之间相互引用。
// a.ts
export var pro1;
var pro2;
export function func1() {
}
function func2() {
}
export class Clazz1 {
}
class Clazz2 {
}
// b.ts
import { pro1, func1, Clazz1 } from "./a";
console.log(pro1)
// 类型定义文件(*.d.ts)
// 帮组我们导入js的工具包, 如jquery
// 推荐使用一个工具 typings
// https://github.com/typings/typings
安装typings工具
npm install typings --global
使用
如搜索安装jquery
typings search jquery
typings install dt~jquery --global --save
如:
typings search semantic-ui
typings install dt~semantic-ui --global --save