ts 与 js 的区别
- 可以做到 early fail,在代码还没有被执行时,系统一旦检测到代码发生类型不匹配,在编译阶段即可发现
- 大型项目测试调试分支覆盖困难,很多代码并不一定能够在所有条件下执行到,运行前的类型检查是减少bug 的一大手段
- 对阅读代码是友好的,在团队合作、代码维护和交接中意义不言自明
- IDE 提供的大量便捷支持和TS本身的语法检查和代码提示自动补全让开发者提高效率,方便重构
- 缺点
安装
npm install -g typescript
初始化项目
tsc --init
将 tsconfig.json 中的
"outDir": "./"注释打开,设置 ts 解析成 js 的输出路径,建议使用 ‘./dist’,否则该文件会报红"outDir": "./dist",
新建 demo.ts 文件
var count:number = 100;console.log(count);
解析当前目录下的 ts 文件
tsc -w
自动运行解析后的文件
nodemon ./dist/demo.js
基础类型
```typescript
数字类型
var count: number = 100; console.log(count); // 100
字符串类型
var msg: string = ‘hello world’; console.log(msg); // ‘hello world’
布尔类型
let isDone: boolean = false; console.log(isDone); // fasle
对象类型
数组 数字类型的数组
let numArr: number[] = [1, 2, 3];
let arr: Array
对象
let obj: Object = { a: 2, b: 3 } console.log(obj) // { a: 2, b: 3 }
any 任意类型
let aa: any = ‘xxx’; console.log(aa); // ‘xxx’
<a name="JsDgM"></a>## 元祖 tuple```typescript# 规定了数组的第一个成员必须为 string 类型,第二个成员必须为 number 类型,否则报错let x: [string, number];x = ['hello', 10];console.log(x); // ['hello', 10]
联合类型
# 规定了 val 变量只能是 string 类型或 number 类型let val: string | numberval = 12console.log("数字为 " + val); // 12val = "test"console.log("字符串为 " + val); // 'test'
接口
- 此接口跟平时说的后台接口是两码事,定义接口就是对一些属性和方法规定,使用接口时必须遵守这些规定
- 可以理解为给一个类设定规则, 有什么属性和有什么方法
(4) 应用场景: : vue路由配置可以使用到(后面会给出代码)
(1) IPerson是接口, 定义employee时指定了它的类型是IPerson
(2)加了?代表是可选属性
# 定义接口interface Person {username: string;age: number;# sex 属性如果使用就必须为 string 或 booleansex?: string | boolean;sayHi: () => string;}# 使用接口let zhangsan: Person = {username: "狂徒",age: 100,sex: '男',sayHi: (): string => {return "Hello!!!";},};let zhangsan1: Person = {username: "狂徒",age: 100,sex: false,sayHi: (): string => {return "Hello!!!";},};let zhangsan2: Person = {username: "狂徒",age: 100,sayHi: (): string => {return "Hello!!!";},};console.log(zhangsan, zhangsan1, zhangsan2); //{ username: '狂徒', age: 100, sex: '男', sayHi: [Function: sayHi] }{ username: '狂徒', age: 100, sex: false, sayHi: [Function: sayHi] }{ username: '狂徒', age: 100, sayHi: [Function: sayHi] }
函数和函数返回值
# 传入的参数为数字类型,输出的为字符串类型function add(x: number, y: number): string {return x + y + '';}console.log(add(1, 2)); // '3'# void 规定函数内不能有返回值function add1(x: number, y: number): void {let sum = x + y;console.log(sum); // 3}console.log(add1(1, 2)) // undefined# lastName为可选参数function buildName(firstName: string, lastName?: string): void {console.log(firstName, lastName);}buildName("hu", 'dsdasdasdsadsadsadd'); // 'hu' 'dsdasdasdsadsadsadd'
泛型
# 输入的是什么类型,返回或输出的就是该类型function identity<T>(arg: T): T {return arg;}console.log(identity<string>('ewwe')) // ewweconsole.log(identity(false)); // false
类和继承
# 定义类class Animal {name: string;constructor(theName: string) {this.name = theName;};move(distanceInMeters: number = 0) {console.log(`${this.name} moved ${distanceInMeters}m.`);}}# 使用类class Snake extends Animal {constructor(name: string) { super(name); }move(distanceInMeters = 5) {console.log("Slithering...");super.move(distanceInMeters);}}class Horse extends Animal {constructor(name: string) { super(name); }move(distanceInMeters = 45) {console.log("Galloping...");super.move(distanceInMeters);}}let sam = new Snake("Sammy the Python");let tom: Animal = new Horse("Tommy the Palomino");sam.move(); // 'Slithering...' 'Sammy the Python moved 5m.'tom.move(34); // 'Galloping...' 'Tommy the Palomino moved 34m.'
枚举
# 如果有初始器,就以初始值处自增,否则从第一个自增enum Direction {Up,Down = 5,Left,Right,}console.log(Direction); //{'0': 'Up','5': 'Down','6': 'Left','7': 'Right',Up: 0,Down: 5,Left: 6,Right: 7}
混入
# 混入对象1class Bird {canFly: boolean;fly() {this.canFly = true;console.log('I can fly')}}# 混入对象2class Fish {canSwim: boolean;swim() {this.canSwim = true;console.log('I can swim')}}# 新对象class FlyFish implements Bird, Fish {constructor() { }canFly: boolean = false;canSwim: boolean = false;fly: () => void;swim: () => void;}function doMixins(derivedCtor: any, baseCtors: any[]) {baseCtors.forEach(baseCtor => {Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {derivedCtor.prototype[name] = baseCtor.prototype[name];});});}doMixins(FlyFish, [Bird, Fish]);let flyFish = new FlyFish();console.log(flyFish.canFly); // falseflyFish.swim(); // I can swim
模块导入导出
- 该部分与 es6 的模块的导入和导出相同,请参考前端模块化 es6 模块化
