1.TypeScript是什么?
TypeScript是微软开发的静态强类型编程语言,它是JavaScript的超集。
2.如何获取TypeScript?
2.1安装TypeScript
$ npm install -g typescript
2.2编译TypeScript文件
$ tsc helloWorld.ts
#helloWorld.ts => helloWorld.js
2.TypeScript的基础类型
2.1 String类型
let str: String = 'hello typescript';
# var str = 'hello typescript';
2.2Boolean类型
let bol: Boolean = true;
# var bol = true;
2.3Number类型
let count: Number = 12;
var count = 12;
2.4Array类型
let list: number[] = [1, 2, 3];
var list = [1, 2, 3];
2.5Enum枚举类型
2.5.1数字枚举
enum result {
Success,
Pending,
Fail
}
# js
var result;
(function (result) {
result[result["Success"] = 0] = "Success";
result[result["Pending"] = 1] = "Pending";
result[result["Fail"] = 2] = "Fail";
})(result || (result = {}));
// 如果指定了第一个值为1,后续则会累加
enum result {
Success = 1,
Pending,
Fail
}
#js
var result;
(function (result) {
result[result["Success"] = 1] = "Success";
result[result["Pending"] = 2] = "Pending";
result[result["Fail"] = 3] = "Fail";
})(result || (result = {}));
result[1] // "Success"
result.Success // 1
2.5.2字符串枚举
enum Direction {
NORTH = "NORTH",
SOUTH = "SOUTH",
EAST = "EAST",
WEST = "WEST",
}
Direction.NORTH // "NORTH"
Direction["NORTH"] // "NORTH"
# js
var Direction;
(function (Direction) {
Direction["NORTH"] = "NORTH";
Direction["SOUTH"] = "SOUTH";
Direction["EAST"] = "EAST";
Direction["WEST"] = "WEST";
})(Direction || (Direction = {}));
Direction.NORTH; // "NORTH"
Direction["NORTH"]; // "NORTH"
2.6 any类型
在Typescript中任何类型都可以被归为 any 类型。这让 any 类型成为了类型系统的顶级类型。
let result: any = 123;
result = "hello";
result = [1, 2, 3];
2.7Unknow类型
就像所有类型都可以赋值给 any,所有类型也都可以赋值给 unknown。这使得 unknown 成为 TypeScript 类型系统的另一种顶级类型(另一种是 any)。
let value: unknown;
value = true; // OK
value = 42; // OK
value = "Hello World"; // OK
value = []; // OK
value = {}; // OK
value = Math.random; // OK
value = null; // OK
value = undefined; // OK
value = new TypeError(); // OK
value = Symbol("type"); // OK
那么any类型与unknown类型有什么区别呢?请参考typescript中any与unknown的区别。
2.8Tuple类型(元组)
元组可以理解为固定长度的数组,可用于定义具有有限数量的未命名属性的类型。
let tupleType: [String, Number] = ["hello", 123]
# js
var tupleType = ["hello", 123];
2.9 Void类型
void 类型像是与 any 类型相反,表示没有任何类型,当一个函数没有返回值时,通常见到返回值为void。
function foo():void {
console.log("this is a message");
}
# js
function foo() {
console.log("this is a message");
}
2.10 Null和undefined类型
TypeScript 里,undefined 和 null 两者有各自的类型分别为 undefined 和 null。
let u: undefined = undefined;
let n: null = null;
# js
var u = undefined;
var n = null;
2.11 Never类型
Never类型指永不存在的类型。 例如,never 类型是那些总是会抛出异常或根本就不会有返回值的函数表达式或箭头函数表达式的返回值类型。
function assertNever(x: never): never {
throw new Error("Unexpected object: " + x);
}
# js
function assertNever(x) {
throw new Error("Unexpected object: " + x);
}