typescript笔记1 环境配置 数据类型

安装

npm install -g typescript
tsc -v

编译

tsc index.ts

配置环境

  1. 生成配置文件tsconfig.json

tsc --init

  1. 在webstorm中启用typescript自动编译
    在这里插入图片描述

降级编译

tsconfig.json

"target": "es5" // 编译目标的js版本

语法检查

tsconfig.json

"strict": true, // 严格检查
"noImplicitAny": true, // 禁用any类型
"strictNullChecks": true, // 检查null/undefined类型赋值

数据类型

定义变量

let flag:boolean = true
  1. 布尔 boolean
  2. 字符串 string
  3. 数字(不区分整数/浮点数) number
  4. 数组 array
let arr:number[] = [1,2,3]
let arr2:Array<number> = [4,5,6]
let arr3:any[] = [1,"abc",false]
  1. 元组类型 tuple
let arr:[string,number,boolean]=["hello",3.14,true]
  1. 枚举 enum
enum Flag {	success = 1, error = 0} // 如果不赋值,默认为索引值0,1,2...,前一个枚举值+1
let f:Flag = Flag.success

7 任意类型 any

let box:any = document.getElementById("box") // 可用于保存对象

8 空 null/undefined

let num:number | null | undefined // 声明联合类型,值可以时多种类型
console.log(num) // 如果不指定undefined,未赋值变量会报错
num = null // 如果不指定null, 变量不可赋值为null

9 没有返回值的函数返回类型 void

function func():void{
	console.log("run")
 	return // 如果包含返回值则报错
}
function func2():number{
	return 1 // 如果返回类型不是number则报错
}

10 不会出现的类型nerver(可以是其他类型的子类型)

function error(message: string): never {
    throw new Error(message);
}

类型别名

type Point = {
	x: number
	y: number
}
type ID = number | string

类型断言

const myCanvas = document.getElementById('canvas1') as HTMLCanvasElement
const myCanvas2 = <HTMLCanvasElement>document.getElementById('canvas1')

文字类型

// 参数align只能传给定选项值
function print(s:string, align: 'left' | 'right' | 'center'){}
// 返回值只能时给定选项值
function compare(a:string, b:string): -1 | 0 | 1{}
// 混合使用不同类型值
function config(config: ConfigType | 'auto'){}

注:对象变量作为参数传值时,因为是可变值,会导致文字类型校验失败,例如

function doRequest(url:string, method: 'GET' | 'POST'){}
const req = {
	url: 'https://a.com',
	method: 'GET'
}
doRequest(req.url,req.method) // 编译报错

正确写法

  1. 使用断言定义变量类型
type Method = 'GET' | 'POST'
const req = {
	method: 'GET' as Method
}
  1. 或 将对象断言为常数
const req = {
	method: 'GET'
} as const
  1. 或 传参时使用断言确保变量类型
doRequest(req.rul, req.method as Method)

类型缩小

typeof 类型守卫

function padLaft(padding: number | string, input: string) {
	// return new Array(padding + 1).join(" ") + input 编译报错
	if (typeof padding === "number") { // 类型守卫,作用域内类型缩小
		return new Array(padding + 1).join(" ") + input 
	}
	return padding + input
}

注: null也属于一种‘object’

function printAll(strs: string | string[] | null){
	if( strs && typeof strs === 'object'){
		// 处理string[]
		// 如果不判断strs, 此分支strs类型为string[] | null
	} else if (typeof strs === 'string'){
		// 处理string
	} else {
	 	// 处理null
	}
}

in

type Fish = {swim: ()=>void}
type Bird = {fly: ()=>void}
function move(animal: Fish | Bird){
	if('swim' im animal){
		animal.swim()
	}
	else{
		animal.fly()
	}
}

instanceof

分配缩小

let x = Math.random() < 0.5 ? 10 : 'hello' // x的类型为 number | string

类型谓词

附加到接受单个参数并返回布尔值的函数,范围值为true时,会把变量类型范围缩小为某具体类型

type Fish = { swim: () => void }
type Bird = { fly: () => void }
function isFish(pet: Fish | Bird): pet is Fish { 
    return (pet as Fish).swim !== undefined
}

function getSmallPet(): Fish | Bird {
    let fish: Fish = {
        swim: () => {
            console.log('fish swim')
        }
    }
    let bird: Bird = {
        fly: () => {
            console.log('bird fly')
        }
    }
    return Math.random() < 0.5 ? fish : bird
}

let pet = getSmallPet()
if (isFish(pet)) { // 通过类型谓词缩小此作用域的类型范围
    pet.swim()
} else {
    pet.fly()
}

never 穷尽性检查

type Shape = Circle | Square | Triangle
function getArea(shape: Shape) {
	switch(shape.kind) {
		case 'circle':
			return ...
		case 'square':
			return ...
		default:
			const _exhaustiveCheck: never = shape // 没有处理到Triangle,此处将编译报错
			return _exhaustiveCheck
	}
}

posted on 2022-04-11 22:37  路过君  阅读(22)  评论(0编辑  收藏  举报

导航