TypeScript 语法大全与示例

基础类型

1. 原始类型

1
2
3
4
5
6
7
8
9
10
11
let isDone: boolean = false;
let count: number = 42;
let name: string = "TypeScript";

// 模板字符串
let sentence: string = `Hello, my name is ${name}`;

// 空值
let unusable: void = undefined;
let u: undefined = undefined;
let n: null = null;

2. 数组

1
2
let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3]; // 泛型语法

3. 元组 (Tuple)

1
2
3
let tuple: [string, number];
tuple = ["hello", 10]; // OK
// tuple = [10, "hello"]; // Error

4. 枚举 (Enum)

1
2
3
4
5
6
enum Color {
Red = 1,
Green,
Blue
}
let c: Color = Color.Green; // 2

5. Any 和 Unknown

1
2
3
4
5
6
7
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

let uncertain: unknown = 4;
uncertain = "could be anything";
// let num: number = uncertain; // Error

6. Never

1
2
3
function error(message: string): never {
throw new Error(message);
}

7. 类型断言

1
2
3
let someValue: any = "this is a string";
let strLength1: number = (<string>someValue).length; // 尖括号语法
let strLength2: number = (someValue as string).length; // as语法

接口 (Interface)

1. 基础接口

1
2
3
4
5
6
7
8
9
interface Person {
name: string;
age?: number; // 可选属性
readonly id: number; // 只读属性
}

function greet(person: Person) {
return `Hello, ${person.name}`;
}

2. 函数类型

1
2
3
4
5
6
7
interface SearchFunc {
(source: string, subString: string): boolean;
}

let mySearch: SearchFunc = function(src, sub) {
return src.search(sub) > -1;
};

3. 可索引类型

1
2
3
4
5
interface StringArray {
[index: number]: string;
}

let myArray: StringArray = ["Bob", "Fred"];

4. 类类型

1
2
3
4
5
6
7
8
9
10
11
interface ClockInterface {
currentTime: Date;
setTime(d: Date): void;
}

class Clock implements ClockInterface {
currentTime: Date = new Date();
setTime(d: Date) {
this.currentTime = d;
}
}

类 (Class)

1. 基础类

1
2
3
4
5
6
7
8
9
10
11
class Animal {
private name: string; // 私有属性

constructor(name: string) {
this.name = name;
}

move(distance: number = 0) {
console.log(`${this.name} moved ${distance}m`);
}
}

2. 继承

1
2
3
4
5
6
7
8
9
class Dog extends Animal {
bark() {
console.log("Woof! Woof!");
}
}

const dog = new Dog("Buddy");
dog.bark();
dog.move(10);

3. 存取器 (getter/setter)

1
2
3
4
5
6
7
8
9
10
11
class Employee {
private _fullName: string = "";

get fullName(): string {
return this._fullName;
}

set fullName(newName: string) {
this._fullName = newName;
}
}

4. 静态属性

1
2
3
4
5
6
7
8
9
10
11
class Grid {
static origin = {x: 0, y: 0};

constructor(public scale: number) {}

calculateDistance(point: {x: number; y: number}) {
let xDist = point.x - Grid.origin.x;
let yDist = point.y - Grid.origin.y;
return Math.sqrt(xDist * xDist + yDist * yDist) * this.scale;
}
}

5. 抽象类

1
2
3
4
5
6
7
8
9
10
11
abstract class Department {
constructor(public name: string) {}

abstract printMeeting(): void; // 必须在派生类中实现
}

class AccountingDepartment extends Department {
printMeeting() {
console.log("Accounting Department Meeting");
}
}

函数

1. 函数类型

1
2
3
4
5
function add(x: number, y: number): number {
return x + y;
}

let myAdd: (x: number, y: number) => number = function(x, y) { return x + y; };

2. 可选参数和默认参数

1
2
3
4
5
6
7
function buildName(firstName: string, lastName?: string) {
return firstName + (lastName ? " " + lastName : "");
}

function buildName2(firstName: string, lastName = "Smith") {
return firstName + " " + lastName;
}

3. 剩余参数

1
2
3
function buildName3(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}

4. 函数重载

1
2
3
4
5
6
7
8
9
function pickCard(x: {suit: string; card: number}[]): number;
function pickCard(x: number): {suit: string; card: number};
function pickCard(x: any): any {
if (typeof x == "object") {
return Math.floor(Math.random() * x.length);
} else if (typeof x == "number") {
return {suit: "hearts", card: x % 13};
}
}

泛型

1. 基础泛型

1
2
3
4
5
function identity<T>(arg: T): T {
return arg;
}

let output = identity<string>("myString");

2. 泛型接口

1
2
3
4
5
interface GenericIdentityFn<T> {
(arg: T): T;
}

let myIdentity: GenericIdentityFn<number> = identity;

3. 泛型类

1
2
3
4
5
6
7
8
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };

4. 泛型约束

1
2
3
4
5
6
7
8
interface Lengthwise {
length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}

高级类型

1. 交叉类型 (Intersection Types)

1
2
3
4
5
6
7
8
9
10
11
interface Person {
name: string;
}

interface Employee {
id: number;
}

type Staff = Person & Employee;

let staff: Staff = { name: "John", id: 123 };

2. 联合类型 (Union Types)

1
2
3
4
5
6
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
return padding + value;
}

3. 类型别名 (Type Aliases)

1
2
3
type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;

4. 字符串字面量类型

1
2
3
4
5
type Easing = "ease-in" | "ease-out" | "ease-in-out";

function animate(dx: number, easing: Easing) {
// ...
}

5. 可辨识联合 (Discriminated Unions)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface Square {
kind: "square";
size: number;
}

interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}

type Shape = Square | Rectangle;

function area(s: Shape) {
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.width * s.height;
}
}

模块

1. 导出

1
2
3
4
5
6
// math.ts
export function add(x: number, y: number): number {
return x + y;
}

export const PI = 3.14;

2. 导入

1
2
3
4
import { add, PI } from "./math";

console.log(add(2, 3)); // 5
console.log(PI); // 3.14

3. 默认导出

1
2
3
4
5
6
7
8
// calculator.ts
export default class Calculator {
// ...
}

// app.ts
import Calc from "./calculator";
let calc = new Calc();

装饰器 (Decorators)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}

@sealed
class BugReport {
type = "report";
title: string;

constructor(t: string) {
this.title = t;
}
}

实用工具类型

1. Partial

1
2
3
4
5
6
7
8
interface Todo {
title: string;
description: string;
}

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate };
}

2. Readonly

1
2
3
4
5
6
7
8
9
interface Todo {
title: string;
}

const todo: Readonly<Todo> = {
title: "Delete inactive users"
};

// todo.title = "Hello"; // Error

3. Record

1
2
3
4
5
6
7
8
9
10
11
interface PageInfo {
title: string;
}

type Page = "home" | "about" | "contact";

const nav: Record<Page, PageInfo> = {
home: { title: "Home" },
about: { title: "About" },
contact: { title: "Contact" }
};

4. Pick 和 Omit

1
2
3
4
5
6
7
8
interface Todo {
title: string;
description: string;
completed: boolean;
}

type TodoPreview = Pick<Todo, "title" | "completed">;
type TodoInfo = Omit<Todo, "completed">;