一、基本类型
1.1继承了javascript的类型设计,有8种基本类型
// 1.boolean类型 只包含true和false两个布尔值
const x:boolean = true;
const y:boolean = false;
// 2.string类型 包含所有字符串
const x:string = 'hello';
const y:string = `${x} world`;//模板字符串
// 3.number类型 包含所有的整数和浮点数
const x:number = 123; //整数
const y:number = 3.14; //浮点数
const z:number = 0xffff;//十六进制数
// 4.bigint类型 包含所有的大整数
const x:bigint = 123n;
const y:bigint = 0xfffn;
/* 注意:bigint与numbe类型不兼容*/
const x:bigint = 123; //报错
const y:bigint = 3.14;//报错
// 5.symbol类型 包含所有的Symbol值
const x:symbol = Symbol();
// 6.object类型 包含了所有的对象、数组和函数
const x:object = { foo : 123 };
const y:object = [1,2,3];
const z:objject = (n:number) => n+1;
// 7.undefined类型 只包含一个值undefined,表示未定义
let x:undefined = un8.defined;//第一个undefined是类型,第二个undefined是值
// null类型 只包含一个值null,表示为空,即此处没有值
const x:null = null;
二、值类型
2.1typescript 规定,单个值也是一种类型,称为“值类型”
let x:'hello';
x = 'hello'; // 正确
x = 'world'; //报错
2.2 typescript推断类型时,遇到const命令声明变量,如果代码里面没有注明类型,就会推断该变量是值类型,这样的推断是合理的,因为const命令声明的变量,一旦声明就不能改变,相当于常量。值类型就意味着不能赋为其他值
// x的类型是 “https”
const x = 'https';
// y的类型是string
const y : string = 'https';
注意,const命令声明的变量,如果赋值为对象,并不会推断为值类型
// x的类型是 { foo : number }
const x = { foo:1 };
三、联合类型
3.1联合类型 指多个类型组成一个新的类型,使用|表示
/* 联合类型A|B表示,任何一个类型只要属于A或B,就属于联合类型A|B*/
let x:string|number;
x = 123; //正确
x = 'abc'; //正确
// 常用写法 某个变量确实可能包含空值,可用联合类型的写法
let name:string|null;
name = 'John';
name = null;
3.2类型缩小 处理联合类型的标准方法
function getPort(scheme:'http'|'https'){
switch(scheme){
case 'http':
return 80;
case 'https':
return 443;
}
}
四、交叉类型
4.1多个类型组成一个新的类型,用&表示
// 主要用途是表示对象的合成
let obj: { foo : string }&{ bar : string }
obj = {foo: 'hello',bar: 'world'};
// 常常用来为对象类型添加新属性
type A = { foo: number };
type B = A & { bar : number };
五、type命令
5.1type命令用来定义一个类型的别名
type Age = number;
let age:Age = 18;
5.2别名的作用域是块级作用域,代码块内定义的别名,影响不到外部
// if代码块内部的类型别名Color,跟外部的Color是不一样de
type Color = 'red';
if(Math.random() < 0.5){
type Color = 'blue';
}
六、typeof运算符
javascript中,typeof运算符是一个一元运算符 返回的是一个字符串,代表操作数的类型
typeof 'foo'; // 'string'
typescript将typeof运算符移植到了类型运算,它的操作依然是一个值,但是返回的不是字符串,而是该值的typescript类型
const a = { x : 0};
type T0 = typeof a; // { x:number }
type T1 = typeof a.x; // number
typeof的参数只能是标识符,不能是需要运算的表达式
let a = 1;
let b:typeof a; // 类型运算 b:number
if (typeof a === 'number') {// number === 'number' 报错
b = a;
}
七、块级类型声明
typescript 支持块级类型声明,即类型可以声明在代码块(用大括号表示)里面,并且只在当前代码块有效
if(true) {
type T = number;
let v : T = 5;
} else {
type T = string;
let v : T = 'hello';
}