typescript是一门融合了部分后端 java思想的前端语言
可以不用,但是不可以不会
ts是强类型语言,打造强大的类型约束系统
TS就是写出约束力更强的系统,约束 JS的弱类型
Typescript是什么
javascript that scales可扩展的 js,ts是 js的超集- 静态类型风格的类型系统
- 静态类型检查:为函数或变量添加约束
- 包括了es6 - es10的语法支持
- ts文档 https://www.typescriptlang.org/
- ts好的兼容性
- 完全兼容 es6+,ts的程序更容易理解
- 第三方库可以单独编写类型文件,declare
- 前端主流框架都用 ts重写
- 丰富的接口提示,代码自动补全,在不同的代码块和定义中进行跳
ts使用场景
- vue3 + vuex
- react hooks
- nodejs & eggjs
- *.d.ts文件,ts的
ts内置类型
- document
- DOM
- BOM
- Date
- interface
- Utility Types
interface Person {name: string,age: number}const user: Person = { name: 'lucy', age: 20 }type IPartial = Partial<IPerson>const user: IPartial = { name: 'lucy' } // Partial 可选的type IOmit = Omit<Person, 'name'> // 忽略的属性const user2: IOmit = { age: 20 }
类型推论
- Type Inference
let str = 'lucy'str = 200 // 报错
联合类型
- Union Types
- |
let str: string | numberstr = 'lucy'str = 200str.length // 报错str.toString() // 必须要访问共同的属性或方法const number: number | string = 25
类型断言
- Type Assertion
- as,
value as number
function getLength(value: string | number) {const str = value as stringif (str.length) {return str.length}// 类型断言const number = value as numberreturn number.toStirng().length}
类型保护
- Type Guard
- typeof
- instanceof
function getLength(value: string | number): number {if (typeof value === 'string') {return value.length}// 类型保护,智能缩小范围return value.toStirng().length}
type类型别名
- type
const sum: (x: number, y: number) => numberconst result = sum(10, 20)// type 类型别名type NumberType = (x: number, y: number, z?:number=20) => numberconst sum: NumberTypeconst result = sum(100, 200)const add = function add(x: number, y: number, z:number=30): number {if (typeof z === 'number') return x + y + zreturn x + y}const add2: NumberType = add// 联合类型type StrOrNumber = string | numberlet result3: StrOrNumber = 123result3 = 'string'
字面量
- 特殊的类型
const str: 'name' = 'name'const number: 1 = 1type Direction = 'Up' | 'Down' | 'Left' | 'Right'const goto: Direction = 'Left' // 只能是以上四选一
交叉类型
&几种类型合并起来- ‘&’和 interface的 extends类似
interface Iname {name: string}type Person = Iname & {age: number}const person: Person = {name: 'lucy', age: 29}
