TypeScript
优点:功能更强大,生态也更健全、更完善
缺点:语言本身多了很多概念,属于渐进式,项目初期会增加一些成本
TS配置:
安装命令:
yarn add typescript --dev
yarn tsc --init
手动编译命令:yarn tsc xx.ts(手动转化xx.ts文件为js)
tsconfig.json配置
//es2015是es6,平时说的es6有时也指包含es2015及之后更新的内容
"target": "es5", //输出的代码转化格式
"lib": ['es2015', 'DOM'],
"outDir": "dist", //编译文件输出文件夹
"rootDir": "src",
"sourceMap": true, //开启源代码映射,方便调试
"strict": true, //开启严格模式,严格模式需要明确指定类型
"strictNullChecks": false, //开启严格模式,严格模式需要明确指定类型是否检查Null
//const a:boolean = null;如果想要不报错,需要设置"strictNullChecks": false
//const h:symbol = Symbol(); target设置为es5时会报错,任何es6中新增对象都会报错,因为设置es5,默认标准库引入的是es5的标准库;
//解决方法:target:'es2015';或者target:'es5',lib:['es2015', 'DOM']
//标准库就是内置对象所对应的声明,代码中使用内置对象就必须引入对应的标准库,否则ts找不到所对应的类型=>报错
//TS中object类型不单指对象,还可以用数组,函数
//const foo:object = function(){}
//const fooA:object = []
//const fooB:object = {}
知识点:
1.ts文件编译
//枚举转化会影响编辑后代码
enum PostStatus {
Draft = 0,
Unpublished = 1,
Published = 2
}
// 枚举类型
const post = {
title: 'Hello',
content: 'Typescript is a typed xx',
status: PostStatus.Draft // 0 1 2
}
编译后:
var PostStatus;
(function (PostStatus) {
PostStatus[PostStatus["Draft"] = 0] = "Draft";
PostStatus[PostStatus["Unpublished"] = 1] = "Unpublished";
PostStatus[PostStatus["Published"] = 2] = "Published";
})(PostStatus || (PostStatus = {}));
// 枚举类型
var post = {
title: 'Hello',
content: 'Typescript is a typed xx',
status: PostStatus.Draft // 0 1 2
};
// 若是代码中不需要获取枚举Key值,则可以将枚举定义成常量
const enum PostStatus {
Draft = 0,
Unpublished = 1,
Published = 2
}
// 枚举类型
const post = {
title: 'Hello',
content: 'Typescript is a typed xx',
status: PostStatus.Draft // 0 1 2
}
//编译后:
// 枚举类型
var post = {
title: 'Hello',
content: 'Typescript is a typed xx',
status: 0 /* Draft */ // 0 1 2
};
2.TS隐式类型推断
let age = 18
Age = '122' // 会报错,因为上面已经推断出age是number类型
3.TS类型断言
const nums = [100, 12, 122]
const res = nums.find(i => i > 0)
const square = res * res
const num1 = res as number
const num2 = res //注意jsx不能使用尖括号格式推断,会与标签有冲突
4.TS中interface中使用分号或者不用符号,只是做代码约束,实际编译后是删除掉的
interface中设置readonly时,变量初始化后不能修改
interface Post{
title: string
subtitle: string
readonly summary: string
}
// 设置接口动态变量,格式如下
interface Test{
[prop: string]: string
}
const test:Test = {title: '2233', sub: '12'}
5.对接口的实现
interface Run {
run(distance: number): void
}
interface Eat {
eat(food: string): void
}
class Person1 implements Eat, Run {
eat(food: string):void{
console.log(`优雅进餐${food}`)
}
run(distance: number){
console.log(`直立行走:${distance}`)
}
}
class Animal implements Eat, Run{
eat(food: string):void{
console.log(`呼噜呼噜${food}`)
}
run(distance: number){
console.log(`爬行:${distance}`)
}
}
6.抽象类
abstract class Animal2 {
eat(food: string):void{
console.log(`呼噜呼噜${food}`)
}
abstract run(distance: number):void
}
class Dog extends Animal2{
run(distance: number){
console.log(`爬行:${distance}`)
}
}
const d2 = new Dog()
d2.eat("test")
d2.run(111)
7.泛型:定义接口或类时未指定具体类型,使用时再传递类型,目的:复用