Skip to content

TypeScript

基础类型

布尔值

TypeScript
let isDone: boolean = false;
let isFinish: boolean = true;

数字

TypeScript里所有的数字都是浮点数,这些浮点数的类型是 number

TypeScript
let decLiteral: number = 2023;  // 十进制
let binLiteral: number = 0b11111100111;  // 二进制
let octLiteral: number = 0o3747;  // 八进制
let hexLiteral: number = 0x7e7;  // 十六进制

字符串

可使用单引号或者双引号表示字符串

TypeScript
let name: string = "Henghua";

数组

TypeScript
let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];

元组

TypeScript
let t: [string, number];
x = ['abc', 10];  // OK
x = [10, 'abc'];  // Error

枚举

enum类型是对JavaScript标准数据类型的一个补充,使用枚举类型可以为一组数值赋予友好的名字。

TypeScript
enum Color {Red, Green, Blue};
let c: Color = Color.Red;

unknown

有时候,我们会想要为那些在编程阶段还不清楚类型的变量指定一个类型。那么我们可以用 unknown 类型来标记这些变量。

TypeScript
let notSure: unknown = 4;
notSure = 'maybe a string instead';
notSure = false;

void

当一个函数没有返回值时,通常会见到返回值类型为 void

TypeScript
function test(): void {
    console.log('test');
}

nullundefined

TypeScript
let u: undefined = undefined;
let n: null = null;

联合类型

Union Types 表示取值可以为多种类型中的一种。

TypeScript
let num: string|number;
num = 6;
num = 'six';

函数

定义

TypeScript
// 有名函数
function add(x: number, y: number): number {
    return x + y;
}

// 匿名函数
let add = function (x: number, y: number): number {
    return x + y;
};

可选参数

通过在参数名旁使用 ? 实现可选参数的功能。

TypeScript
function buildName(firstName: string, lastName?: string) {
    if (lastName) {
        return firstName + ' ' + lastName;
    } else {
        return firstName;
    }
}

剩余参数

剩余参数会被当成个数不限的可选参数。可以一个没有,同样可以有多个。使用 ... 进行定义。

TypeScript
function getName(firstName: string, ...restOfName: string[]) {
    return firstName + ' ' + restOfName.join(' ');
}

定义

TypeScript
class Person {
    private name: string;
    private age: number;

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

    public getPersonInfo(): string {
        return `My name is ${this.name} and age is ${this.age}.`;
    }
}

let person = new Person('Henghua', 20);

继承

关键字:extends

TypeScript
class Employee extends Person {
    private department: string;

    constructor(name: string, age: number, department: string) {
        super(name, age);
        this.department = department;
    }
}

模块

关键字:export, import

TypeScript
export class NewsData {
    title: string;
    content: string;

    constructor(title: string, content: string) {
        this.title = title;
        this.content = content;
    }
}
TypeScript
import { NewsData } from '../common/NewsData';

迭代器

当一个对象实现了 Symbol.iterator 属性时,就认为它是可迭代的。

TypeScript
let list = [4, 5, 6];

// for in 语句对下标进行遍历
for (let i in list) {
    console.log(i);  // 0 1 2
}

// for of 语句对元素进行遍历
for (let i of list) {
    console.log(i);  // 4 5 6
}