目录
Typescript类型
原始类型
number、string、boolean、null、undefined、symbol(ES6引入)、bigint(ES11引入)
const myName: string = 'yf';
const age: number = 18;
const male: boolean = false;
const undef: undefined = undefined;
const nul: null = null;
const bigintVar1: bigint = 90071992547409212n;
const bigintVar2: bigint = BigInt(9007199254740991);
const symbolVar: symbol = Symbol('unique');
null和undefined
null表示一个空值,typeof null = 'object',null instanceof Object = false。
undefined表示数据没赋值或者函数没有返回会默认返回undefined。
在tsconfig.json中没有开启strictNullChecks检查的情况下,null和undefined两种类型会被视作其他类型的子类型(不包括never),开启后只能赋值自己。
void
用于函数中无返回值,可以写return但后面不能跟值。需要通过函数声明加返回值才会有void类型检查。
function warnUser(): void {
console.log("This is my warning message");
return;
}
注意
通过变量名后面跟函数类型限定参数和返回类型,赋值时不会对参数以及返回值进行类型检测,只检查是函数类型。只有在运行该函数才会检查。
type aFun= (a: number) => void
let func: aFun = ()=>111 // 不会有类型报错
// let a:number = func() // 会报错,
// Type 'void' is not assignable to type 'number'
// An argument for 'a' was not provided.
never
用于函数抛出报错。
let throwErrorFun:()=>never = () => { throw new Error('aa') }
// let a:never = new Error('a') //报错
let a:never = (() => { throw new Error('aa') })()
元组
用于定义数组中每位的类型。
let a: string[] = ['a','b']
具名元组
名称没有实际的意思,可以增加代码的易懂阅读性。注意元组中要不全部使用类型(aa的形式)要不全部使用具名(bb的形式)。
type BB = 'bb'
type CC = 'cc'
let aa:[BB,CC] = ['bb','cc']
let bb:[a:BB,b:CC] = ['bb','cc']
类型运算符
|运算符
或连接表示需要满足其中一种类型
type Name1 = { name: string; }
type User1 = Name1 | { age: number; } //type User = {name: string}|{ age: number;}
let user1: User1 = { name: 'yf' } // 只需要满足其中一个类型
&运算符
与连接表示需要同时满足两个类型
type Name2 = { name: string; }
type User2 = Name2 & { age: number; } // type User = {name: string; age: number;}
let user2: User1 = { name: 'yf', age: 18 } // 两个类型需要都满足
类型关键字
Infer
表示在 extends 条件语句中以占位符出现的用来修饰数据类型的关键字,被修饰的数据类型等到使用时才能被推断出来。
示例
// 定义了一个接口Customer,它描述了一个具有name(字符串类型)和moneyPaid(数字类型)属性的对象
interface Customer {
name: string
moneyPaid: number
}
// 定义了一个函数类型,接收一个Customer类型的参数并返回一个字符串
type custFuncType = (cust: Customer) => string
// 定义了一个泛型类型inferType<T>,这是理解的重点。这是一个条件类型,它使用了infer关键字,这里是一个三元判断返回类型P或T
// 表示传入的T如果是函数且只有1个参数则返回参数的类型,否则返回函数本身
type inferType<T> = T extends (params: infer P) => any ? P : T
// 定义了inferResultType类型别名,它是通过将前面定义的custFuncType类型作为参数传递给inferType得到的
type inferResultType = inferType<custFuncType> // type inferResultType = Customer
let inferVariable: inferResultType = { name: "yf", moneyPaid: 9999 };
//如果custFuncType的函数没有参数,这里的inferResultType相当于any
extends
1.用于类型集合表示A extends B,表示A是B中的一个子类型。
2.用于类A extends B表示,B类中的属性在A类中需要被实现(A>B)。
type MyExtends = b extends bb ? 1 : 2
//bb中的say属性在b类中没有被实现,所以返回三元中false的项即 type MyExtends1 = 2
type MyExtends1 = number extends number|string ? 1 : 2 // type MyExtends1 = 1
typeof
可以将变量转化为类型
function square(a: number) { return a * a }
type squareType = typeof square;//type squareType = (a: number) => number
keyof
返回对象类型属性名的集合
type Man = {
name: string;
age: number;
}
type MyKeyof = keyof Man // type M