TS概述
TS是JS的超集,本质上向JS添加了可选的静态类型和基于类的面向对象编程,可以解决Js类型错误的问题(即在预期某种类型的值的地方写入了其它的类型,导致JS无法理解库的API而报错)
使用工具
- 安装vscode
- 安装node.js
- 安装typeScript编译器
npm install -g typescript
编译优化
1-解决TS与JS冲突问题
tsc --init #生成配置文件 tsconfig.json
2-自动编译
tsc --watch
3-发出错误
tsc -noEmitOnError hello.ts
严格模式
- tsconfig.json
"strict": true开启类型验证"noImplicitAny": true"strictNullChecks": true
数组
// type 是数据类型
let arr: type[] = [1, 2, 3]
let arr: Array<type> = [1, 2, 3]
any
- 不希望某个特定值导致类型检查错误
let obj: any = {
x: 1
}
联合类型
- 用 | 进行连接
function getName(name: string[] | string) {
if (Array.isArray(x)) {
console.log(x.join(' and '))
} else {
console.log(x)
}
}
类型别名
- 用type定义
type Point = {
x: number;
y: number;
}
function printCoord(pt: Point) {
console.log(pt);
}
printCoord({
x: 190,
y: 200
})
type ID = number | string
function printID(id: ID) {
console.log(id)
}
printID(12)
扩展类型
// 向现有类型添加字段
interface MyWindow {
count: number
}
interface MyWindow {
title: string
}
const w: MyWindow = {
title: 'hello ts',
count: 100
}
// 或者
interface haha {
name2: string,
age2: number
}
interface xixi extends haha {
sex: string
}
const person: xixi = {
name2: 'gout',
age2: 33,
sex: 'man'
}