TypeScript 類型系統的最佳實踐包括以下幾點:
function greet(name: string): string {
return `Hello, ${name}!`;
}
interface Person {
name: string;
age: number;
}
type User = Person & {
email: string;
};
type StringOrNumber = string | number;
type PersonWithAddress = Person & {
address: string;
};
type Color = 'red' | 'green' | 'blue';
interface Person {
name: string;
age?: number; // 可選類型
readonly address: string; // 只讀類型
}
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
function isNumber(value: any): value is number {
return typeof value === 'number';
}
type Greeting = `Hello, ${string}!`;
function identity<T>(arg: T): T {
return arg;
}