Skip to main content

TypeScript 基础类型

原始类型

// 布尔值
let isDone: boolean = false;

// 数字
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;

// 字符串
let color: string = "blue";
let sentence: string = `Hello, ${color}`;

// null 和 undefined
let u: undefined = undefined;
let n: null = null;

// void
function warnUser(): void {
console.log("This is a warning message");
}

// never
function error(message: string): never {
throw new Error(message);
}

对象类型

Array

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

Tuple

let x: [string, number];
x = ["hello", 10]; // OK
x = [10, "hello"]; // Error

Object

let obj: object = {};
let obj2: { name: string; age: number } = { name: "Tom", age: 25 };

Interface

interface Person {
name: string;
age: number;
readonly id: number; // 只读属性
gender?: string; // 可选属性
}

let tom: Person = {
name: "Tom",
age: 25,
id: 1
};

特殊类型

Any

let notSure: any = 4;
notSure = "maybe a string";
notSure = false;

Unknown

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

Type Assertions (类型断言)

let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;
// 或
let strLength: number = (<string>someValue).length;