1、数组类型
- 普通指定类型数组声明
const arr: number[] = [1,2,3,4] or
const arr: Array<number> = [1,2,3,4]
- 指定多个类型声明
const arr1: (number | boolean | string)[] = [1,2,3,4,'a','c',true] or
const arr: Array<number | boolean | string> = [1,2,3,4,'a','c',true]
- 指定任意类型
const arr2: any[] = [1,2,3,4,'a','c',true] or
const arr3: Array<any> = [1,2,3,4,'a','c',true]
2、函数类型
-
声明式函数,参数类型在参数后面,返回值类型在参数括号后面指定
function add(a: number, b: number): number { return a + b }
-
箭头函数,参数类型
const add1 = (a: number, b: number): number => { return a + b }
-
箭头函数的复杂写法,其中这一段(a: number, b: number) => number 是对add2的类型声明,后面的 (a: number, b: number) => a + b是函数内容
const add2: (a: number, b: number) => number = (a: number, b: number) => a + b
-
any、void、unknown
any 任意类型 void 永远不存在类型 unknown 未知类型
3、元组和枚举
-
元组: 固定类型 + 长度的数组
const teachInfo: [string,string,number] = ['aa','ccc',23]
-
枚举类型
enum Gender { Male, FeMale } console.log(Gender.Male)
4、interface的绕开多余类型检查
-
这里在传入参数时,如果一定要传入这个参数的话,可以用as作类型断言,来绕开多余类型检查
interface MyType { color: string }
const getTypes = (myType: MyType) => { return
${myType.color}}getTypes({ color: 'red', num: 12 } as MyType)
-
类型签名,可以在interface里加一个[props: string]: any,指定值为任意类型,这样就可以不限制了
interface MyType { color: string [props: string]: any }
const getTypes = (myType: MyType) => { return
${myType.color}}getTypes({ color: 'red', num: 12, isA: false, f: () => {} })
-
interface可以指定任意类型,但是如果声明了数字、字符串等基本类型,是没有prototype上的属性和方法的
5、泛型
在定义函数、接口或类的时候不预先指定数据类型,而在使用时再指定类型的特性
-
在没有泛型的情况下,像下面的这两个函数,几乎同样的操作,需要声明两个
const pushArr = (arr: string[], item: string): string[] => { arr.push(item) return arr }
const pushNumberArr = (arr: number[], item: number): number[] => { arr.push(item) return arr }
-
若有了泛型,则可以直接使用一个函数搞定
const pushArr = (arr: T[], item: T): T[] => { arr.push(item) return arr }
-
例如,交换函数
const swapGen = <T,U>(a: T, b: U): [U,T] => { return [b,a] }