TypeScript

TypeScript

  • TypeScript 是 JavaScript 的一个超集,在 JavaScript 的基础上增加了静态类型检查的超集。可以编译成纯 JavaScript,编译出来的 JavaScript 可以运行在任何浏览器上。

基础类型

string

1
let name: string = "Alice";

number

1
let age: number = 30;

boolean

1
let isDone: boolean = true;

array

1
let list: number[] = [1, 2, 3];

tuple

1
2
// 示已知类型和长度的数组
let person: [string, number] = ["Alice", 30];

enum

1
2
// 定义一组命名常量
enum Color { Red, Green, Blue };

any

1
2
// 任意类型,不进行类型检查
let value: any = 42;

void

1
2
// 无返回值(常用于函数)
function log(): void {}

null

1
2
// 表示空值
let empty: null = null;

undefined

1
2
// 表示未定义
let undef: undefined = undefined;

never

1
2
// 表示不会有返回值
function error(): never { throw new Error("error"); }

object

1
2
// 表示非原始类型
let obj: object = { name: "Alice" };

union

1
2
3
4
// 表示一个变量可以是多种类型之一
let id: string | number;
id = "123";
id = 456;

unknown

1
2
// 不确定类型,需类型检查后再使用
let value: unknown = "Hello";

变量声明

1
var [变量名] : [类型] = 值;
  • 当类型没有给出时,TypeScript 编译器利用类型推断来推断类型。

作用域

1
2
3
4
5
6
7
8
9
10
11
12
13
var global_num = 12          // 全局变量
class Numbers {
num_val = 13; // 实例变量
static sval = 10; // 静态变量

storeNum():void {
var local_num = 14; // 局部变量
}
}
console.log("全局变量为: "+global_num)
console.log(Numbers.sval) // 静态变量
var obj = new Numbers();
console.log("实例变量: "+obj.num_val)

函数

1
2
3
4
function function_name(param1[:type],param2[:type] = default_value):return_type { 
// 语句
return value;
}

匿名函数

1
2
3
4
5
6
var res = function( [arguments] ) { ... }
// 自调用
(function () {
var x = "Hello!!";
console.log(x)
})()

Map

1
2
3
4
5
6
7
8
9
10
let map = new Map([
["key1", "value1"],
["key2", "value2"]
]);
map.set('key1', 'value1');
const value = map.get('key1');
const exists = map.has('key1');
const removed = map.delete('key1');
map.clear();
const size = map.size;

接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
interface IPerson { 
firstName:string,
lastName:string,
sayHi: ()=>string
}

var customer:IPerson = {
firstName:"Tom",
lastName:"Hanks",
sayHi: ():string =>{return "Hi there"}
}

console.log("Customer 对象 ")
console.log(customer.firstName)
console.log(customer.lastName)
console.log(customer.sayHi())

var employee:IPerson = {
firstName:"Jim",
lastName:"Blakes",
sayHi: ():string =>{return "Hello!!!"}
}

console.log("Employee 对象 ")
console.log(employee.firstName)
console.log(employee.lastName)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Car { 
// 字段
engine:string;

// 构造函数
constructor(engine:string) {
this.engine = engine
}

// 方法
disp():void {
console.log("函数中显示发动机型号 : "+this.engine)
}
}

// 创建一个对象
var obj = new Car("XXSY1")

// 访问字段
console.log("读取发动机型号 : "+obj.engine)

// 访问方法
obj.disp()

泛型

1
2
3
4
5
6
7
8
9
10
11
12
function identity<T>(arg: T): T {
return arg;
}

interface KeyValuePair<K, V> {
key: K;
value: V;
}

function printArray<E>(arr: E[]): void {
arr.forEach(item => console.log(item));
}

模块

1
2
3
4
/// <reference path = "IShape.ts" /> 
export interface IShape {
draw();
}
1
2
3
4
5
6
import shape = require("./IShape"); 
export class Circle implements shape.IShape {
public draw() {
console.log("Cirlce is drawn (external module)");
}
}
1
2
3
4
5
6
import shape = require("./IShape"); 
export class Triangle implements shape.IShape {
public draw() {
console.log("Triangle is drawn (external module)");
}
}
1
2
3
4
5
6
7
8
9
10
import shape = require("./IShape"); 
import circle = require("./Circle");
import triangle = require("./Triangle");

function drawAllShapes(shapeToDraw: shape.IShape) {
shapeToDraw.draw();
}

drawAllShapes(new circle.Circle());
drawAllShapes(new triangle.Triangle());