启用TypeScript
- webpack+babel
- vite2
https://cn.vitejs.dev/guide/#scaffolding-your-first-vite-project
- tsc ( typescript compilter
λ tsc 1.ts
类型 v.s. 类
JS基本类型
- 简单类型
null undefined
string boolean number
symbol bigint
- 复杂类型
object
- 特殊的
typeof
typeof 函数 → “function”
typeof null → “object”
JS中的类
只针对object
面向对象编程
- 基于class关键字
- 基于原型 ```javascript class Person{ 属性1 属性2 属性3 方法1 方法2 方法3 }
const p1 = new Person() p1.属性1 p1.方法1()
> **类型是对所有数据的分组,类只对对象的抽象编程**
**类型的作用**
1. 减少bug
1. 提示
<a name="BAwJD"></a>
# TS支持的JS类型
```jsx
const a: undefined = undefined
const b: null = null
const c: string = 'hi'
const d: boolean = true
const e: symbol = Symbol('hi')
const f: bigint = 123n
const obj: Object={} //类
const obj0: object={} //类型
const arr: Array<string | number | null> = ['1','2',3,null]
//类型写在函数体
const add = (a: number,b: number): number => a+b
//类型写在:后面
const add0:(a: number,b: number)=> number = (a,b) => a+b
//type缩写
type Add = (a: number,b: number)=> number
const add1: Add = (a,b) => a+b
//有属性用interface
interface AddWithProps{
(a: number,b: number) : number
xxx: string
}
const add2: AddWithProps = (a,b) => a+b
add2.xxx = 'yyy'
TS额外的类型
let a: any = 1
a = 'hi'
type B = { name: string }
let b: unknown = JSON.parse('{"name":"frank"}')
console.log((b as B).name) //断言
let print: () => void = function () {
console.log(1)
}
type Dir = 1 | 2 | 3 | 4 | undefined
let dir: Dir = 1
switch (dir) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case undefined:
break;
default:
console.log(dir) //dir: never
break;
}
//tuple 元组
let p: [number, number] = [100.200]
let p2: [number, string, boolean] = [100, 'x', true]
enum Dir1 { 东, 南, 西, 北 }
let d2: Dir2 = Dir1.东 //0
let d3: Dir3 = Dir1.西 //2
console.log(d2, d3) //0 2