TypeScript 基础类型哪些事儿

简单基础类型

1.数字number

text
复制代码
//掌握:支持整型和浮点 //了解:支持十六进制字面量,二进制,八进制字面量 const age: number = 18 const num: number = 0.9 const num1: number = 0b11 //0b:二进制 const num2: number = 0o77 //0o:八进制 const num3: number = 0xf //0x:十六进制 console.log(0b11,0o77,0xf) //3,63,15

2.字符串string

text
复制代码
//掌握:支持模板字符串,支持拼接 const name: string = '毛皮' const str: string = 'hello' const str1: string = str+':'+name // 'hello,毛皮' const str2: string = `hi,${name}` // 'hi,毛皮'

3.布尔boolean

text
复制代码
const isDo: boolean = true

4.null 和 undefined

text
复制代码
const empty: null = null let u:undefined = undefined

5.bigInt

text
复制代码
const big: bigInt = 123456789n

6.symbol

text
复制代码
let sym: symbol = Symbol('毛皮')

复杂基础类型

1.数组array

text
复制代码
const ary1: number[] = [1,2,3] // 推荐 const ary2: (number | string)[] = [1,'2',3] // 推荐 const ary3: Array<number> = [1,2,3] const ary4: Array<number | boolean> = [1,2,true]

2.对象object

text
复制代码
let obj: object obj = { name: '毛皮' }

3.元组Tuple

重点:规定元素数量和类型的数组

text
复制代码
了解:可以通过数组方法添加已有的元素类型的元素到数组,并且添加的元素不支持直接访问,需通过数组方法访问。(不推荐添加元素,违背了元组式不可变的初衷) const tup: [string,number] = ['hello',9527] tup.push('world') tup[2] // 拿不到数据 tup.slice(2) // world tup.push(true) //报错:元组元素类型是string,number

4.枚举

text
复制代码
// 了解:自带类型的对象,自动增长 enum Roles { USER, ADMIN, } console.log(Roles['0']) //USER console.log(Roles['1']) //ADMIN // 掌握:常量枚举 const enum DIRE { Up = "UP", Down = "DOWN", Left = "LEFT", Right = "RIGHT", } console.log(DIRE.Up) // UP console.log(DIRE['0']) //报错:常量枚举要直接访问属性

5.any|void|never

text
复制代码
// any:任意类型 let value: any; value = 123; value = "abc"; value = false; const array: any[] = [1, "a", true];
text
复制代码
// void:没有类型,常用于函数返回值,表示不返回值 function():void{}
text
复制代码
// never:永远不会出现的类型,常用于函数校验参数 //保护类型,保障程序的完整性 针对不同类型做不同处理 function validate(value: never) {} function say(text: string | number | boolean) { if (typeof text === 'string') { return } if (typeof text === 'number') { return } if (typeof text === 'boolean') { return } //永远不能到这里,不然就是 string | number | boolean =>给never validate(text) }

函数function类型

直接定义

text
复制代码
//掌握:b表示可选类型,可传可不传,可选类型要放在形参最后一位 //a:具有默认值 function say(a:string='1',b?:string):string{ return a+b }

接口定义

text
复制代码
interface Isay = { (a: string, b?: string): string; } const say:Isay = (a=1,b)=>{ return a+b }

类型别名定义

text
复制代码
type Isay = (a: string, b?: string): string; const say:Isay = (a=1,b)=>{ return a+b }
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP