TypeScript类型 #
一、类型系统概述 #
TypeScript为JavaScript添加了静态类型系统,在编译时进行类型检查,帮助发现潜在错误。Deno原生支持TypeScript,无需额外配置。
二、接口(Interface) #
2.1 基本接口 #
typescript
interface User {
id: number;
name: string;
email: string;
}
const user: User = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
console.log(user.name); // Alice
2.2 可选属性 #
typescript
interface Product {
id: number;
name: string;
description?: string;
price?: number;
}
const product: Product = {
id: 1,
name: "Widget"
};
console.log(product.description); // undefined
2.3 只读属性 #
typescript
interface Config {
readonly apiKey: string;
readonly endpoint: string;
timeout?: number;
}
const config: Config = {
apiKey: "secret-key",
endpoint: "https://api.example.com"
};
// config.apiKey = "new-key"; // 错误:只读属性
config.timeout = 5000; // 允许修改
2.4 函数类型 #
typescript
interface MathOperation {
(a: number, b: number): number;
}
const add: MathOperation = (a, b) => a + b;
const subtract: MathOperation = (a, b) => a - b;
console.log(add(10, 5)); // 15
console.log(subtract(10, 5)); // 5
2.5 可索引类型 #
typescript
interface StringArray {
[index: number]: string;
}
const names: StringArray = ["Alice", "Bob", "Charlie"];
console.log(names[0]); // Alice
interface StringDictionary {
[key: string]: string | number;
length: number;
}
const dict: StringDictionary = {
name: "Alice",
age: 25,
length: 2
};
2.6 接口继承 #
typescript
interface Animal {
name: string;
age: number;
}
interface Dog extends Animal {
breed: string;
bark(): void;
}
const dog: Dog = {
name: "Buddy",
age: 3,
breed: "Golden Retriever",
bark() {
console.log("Woof!");
}
};
dog.bark(); // Woof!
2.7 接口实现 #
typescript
interface Serializable {
serialize(): string;
}
class User implements Serializable {
constructor(
public id: number,
public name: string
) {}
serialize(): string {
return JSON.stringify({ id: this.id, name: this.name });
}
}
const user = new User(1, "Alice");
console.log(user.serialize()); // {"id":1,"name":"Alice"}
三、类型别名(Type Alias) #
3.1 基本类型别名 #
typescript
type ID = string | number;
type Name = string;
type Age = number;
const userId: ID = "user-123";
const userName: Name = "Alice";
const userAge: Age = 25;
3.2 对象类型别名 #
typescript
type Point = {
x: number;
y: number;
};
type User = {
id: number;
name: string;
email: string;
};
const point: Point = { x: 10, y: 20 };
const user: User = { id: 1, name: "Alice", email: "alice@example.com" };
3.3 联合类型 #
typescript
type Status = "pending" | "active" | "completed" | "cancelled";
type StringOrNumber = string | number;
type Result = Success | Error;
interface Success {
success: true;
data: string;
}
interface Error {
success: false;
error: string;
}
function handleResult(result: Result) {
if (result.success) {
console.log("Data:", result.data);
} else {
console.log("Error:", result.error);
}
}
3.4 交叉类型 #
typescript
type Name = { name: string };
type Age = { age: number };
type Email = { email: string };
type User = Name & Age & Email;
const user: User = {
name: "Alice",
age: 25,
email: "alice@example.com"
};
3.5 接口vs类型别名 #
typescript
// 接口可以被扩展和实现
interface IUser {
name: string;
}
interface IEmployee extends IUser {
employeeId: string;
}
// 类型别名更灵活
type TUser = {
name: string;
};
type TEmployee = TUser & {
employeeId: string;
};
// 类型别名可以表示联合类型
type ID = string | number; // 接口不能这样做
四、泛型(Generics) #
4.1 泛型函数 #
typescript
function identity<T>(arg: T): T {
return arg;
}
const str = identity<string>("hello");
const num = identity(42); // 类型推断
console.log(str); // hello
console.log(num); // 42
4.2 泛型接口 #
typescript
interface Container<T> {
value: T;
getValue(): T;
}
const stringContainer: Container<string> = {
value: "hello",
getValue() {
return this.value;
}
};
const numberContainer: Container<number> = {
value: 42,
getValue() {
return this.value;
}
};
4.3 泛型类 #
typescript
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
peek(): T | undefined {
return this.items[this.items.length - 1];
}
isEmpty(): boolean {
return this.items.length === 0;
}
}
const numberStack = new Stack<number>();
numberStack.push(1);
numberStack.push(2);
console.log(numberStack.pop()); // 2
const stringStack = new Stack<string>();
stringStack.push("hello");
console.log(stringStack.peek()); // hello
4.4 泛型约束 #
typescript
interface Lengthwise {
length: number;
}
function logLength<T extends Lengthwise>(arg: T): number {
console.log(arg.length);
return arg.length;
}
logLength("hello"); // 5
logLength([1, 2, 3]); // 3
logLength({ length: 10 }); // 10
// logLength(123); // 错误:number没有length属性
4.5 多类型参数 #
typescript
function pair<K, V>(key: K, value: V): [K, V] {
return [key, value];
}
const p1 = pair("name", "Alice");
const p2 = pair(1, true);
console.log(p1); // ["name", "Alice"]
console.log(p2); // [1, true]
4.6 默认类型参数 #
typescript
interface ApiResponse<T = unknown> {
data: T;
status: number;
message: string;
}
const response1: ApiResponse = {
data: null,
status: 200,
message: "OK"
};
const response2: ApiResponse<string> = {
data: "Success",
status: 200,
message: "OK"
};
五、高级类型 #
5.1 Partial #
typescript
interface User {
id: number;
name: string;
email: string;
}
function updateUser(user: User, updates: Partial<User>): User {
return { ...user, ...updates };
}
const user: User = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
const updated = updateUser(user, { name: "Bob" });
console.log(updated.name); // Bob
5.2 Required #
typescript
interface Config {
host?: string;
port?: number;
debug?: boolean;
}
const config: Required<Config> = {
host: "localhost",
port: 3000,
debug: false
};
5.3 Readonly #
typescript
interface User {
name: string;
email: string;
}
const user: Readonly<User> = {
name: "Alice",
email: "alice@example.com"
};
// user.name = "Bob"; // 错误:只读
5.4 Pick #
typescript
interface User {
id: number;
name: string;
email: string;
password: string;
}
type PublicUser = Pick<User, "id" | "name" | "email">;
const publicUser: PublicUser = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
5.5 Omit #
typescript
interface User {
id: number;
name: string;
email: string;
password: string;
}
type SafeUser = Omit<User, "password">;
const safeUser: SafeUser = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
5.6 Record #
typescript
type Role = "admin" | "user" | "guest";
const permissions: Record<Role, string[]> = {
admin: ["read", "write", "delete"],
user: ["read", "write"],
guest: ["read"]
};
console.log(permissions.admin); // ["read", "write", "delete"]
5.7 ReturnType #
typescript
function createUser(name: string, age: number) {
return {
name,
age,
createdAt: new Date()
};
}
type User = ReturnType<typeof createUser>;
const user: User = {
name: "Alice",
age: 25,
createdAt: new Date()
};
六、类型守卫 #
6.1 typeof类型守卫 #
typescript
function process(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
6.2 instanceof类型守卫 #
typescript
class Dog {
bark() { console.log("Woof!"); }
}
class Cat {
meow() { console.log("Meow!"); }
}
function makeSound(animal: Dog | Cat) {
if (animal instanceof Dog) {
animal.bark();
} else {
animal.meow();
}
}
6.3 in操作符 #
typescript
interface Bird {
fly(): void;
}
interface Fish {
swim(): void;
}
function move(animal: Bird | Fish) {
if ("fly" in animal) {
animal.fly();
} else {
animal.swim();
}
}
6.4 自定义类型守卫 #
typescript
interface Success {
success: true;
data: string;
}
interface Error {
success: false;
error: string;
}
function isSuccess(result: Success | Error): result is Success {
return result.success === true;
}
function handleResult(result: Success | Error) {
if (isSuccess(result)) {
console.log("Data:", result.data);
} else {
console.log("Error:", result.error);
}
}
七、类型推断 #
7.1 变量推断 #
typescript
let x = 10; // 推断为number
let y = "hello"; // 推断为string
let z = [1, 2, 3]; // 推断为number[]
// x = "string"; // 错误
7.2 函数返回值推断 #
typescript
function add(a: number, b: number) {
return a + b; // 推断返回number
}
function greet(name: string) {
return `Hello, ${name}!`; // 推断返回string
}
7.3 上下文推断 #
typescript
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => {
console.log(num.toFixed(2)); // num推断为number
});
八、总结 #
本章学习了:
- 接口的定义和使用
- 类型别名的定义和使用
- 泛型函数、接口、类
- 高级类型工具
- 类型守卫
- 类型推断
下一章,我们将学习运算符。
最后更新:2026-03-28