一、TypeScript是什么?
TypeScript是微软开发的一个开源的编程语言,通过在JavaScript的基础上添加静态类型定义构建而成。TypeScript通过TypeScript编译器或Babel转译为JavaScript代码,可运行在任何浏览器,任何操作系统。
二、使用步骤
1.全局安装tsc
- 运行 npm insatll tsc -g, 将tsc安装到全局
2.初始化ts配置文件
- 运行tsc --init,会产生一个tsconfig.json文件,里面是ts的配置信息
3.创建一个ts文件
- 创建一个1.ts文件
4.编写第一行ts代码,并运行
- let a = 1;
- 运行 tsc 1.ts
- 此时会生成一个1.js文件,那么第一个ts文件就运行成功了
三、ts中的基本数据类型
- 基本类型
let isShow: boolean = true;
let a: number = 10;
let b: string = 'hello';
let arr1: number[] = [1, 2, 3]; // arr1和arr2等价
let arr2: Array<number> = [4, 5, 6]; // arr1和arr2等价
- 元组类型 tuple
// 数量和类型已知的数组
let start: [number, string, boolean, number[]] = [1, 'hello', true, [1, 2, 3]];
- 枚举类型 enum
// 1) 普通枚举
enum Person{
NAME,
AGE
}
console.log(Person.NAME, Person[Person.NAME]); // 0 NAME
console.log(Person.AGE, Person[Person.AGE]); // 1 AGE
// 2) 常量枚举
const enum Colors{
RED,
BLUE,
YELLOW,
GREEN
}
console.log([Colors.RED, Colors.BLUE, Colors.YELLOW, Colors.GREEN]);
- 任意类型 any
// 变量定义为any类型,那么就不进行类型检查了
let app1: any = document.getElementById('app');
app1.style.color = "#fff";
let app2: (HTMLElement | null) = document.getElementById('app');
// 如果app2为null,那么需要加非空断言 app2!.style.color
app2!.style.color = "#ccc";
// null undefined 是其他类型的子类型
let j: number = 1;
j = 2;
/* j = undefined;
j = null;
*/
// 注意:如果设置strictNullChecks为true,那么不能直接将值改为null undefined
// 解决办法1:
let k: number | undefined | null = 1;
k = 2;
k = undefined;
k = null;
// 解决办法2
let m: number = 1;
m = 2;
let m1:undefined = undefined;
let m2: null = null;
let m3: any = undefined;
let m4: any = null;
- never 类型
// 作为不会返回的函数的返回值类型
function error(msg: string):never {
throw new Error('error!!!');
// 抛出异常直接就结束了,并不会打印,此时就是never类型
console.log(msg);
}
function loop(): never{
while (true) {
console.log('迭代');
}
// 此处不会执行,所以是never类型
console.log('结束')
}
function fn(a: number | string) {
if (typeof a === 'number') {
console.log(a);
} else if (typeof a === 'string') {
console.log(a);
} else {
console.log(a); // never,不会执行
}
}
- void 类型
// 函数没有返回值,那么就是void类型
// 注意:strictNullChecks为true时,不能将null赋值给void,strictNullChecks为false时,可以将null赋值给void
// void和never类型的区别:
// 1)void类型可以被赋值为null或者undefined,never不行
// 2)返回为void类型的函数还能执行,返回为never类型的函数不能执行(要么抛出异常,要么不执行)
function fun(): void {
// return undefined;
// return null;
}
- symbol 类型
// 用来记录唯一且不变的值
const n1 = Symbol('key');
const n2 = Symbol('key');
// This condition will always return 'false' since the types 'typeof n1' and 'typeof n2' have no overlap.
// console.log(n1 == n2);
- bigint 类型
// 安全存储超大数字
// const max = Number.MAX_SAFE_INTEGER; // 表示js能记录的最大值 2**53-1
// console.log(max + 1 === max + 2); // true 因为已经是最大值了无法计算,所以是true
const max = BigInt(Number.MAX_SAFE_INTEGER);
console.log(max + BigInt(1) === max + BigInt(2)); // false 转成BigInt类型后可安全计算,所以是false
总结
记录下ts的一些知识,下次再见