TypeScript 實用工具型別
TypeScript 提供了大量的型別,可以幫助處理一些常見的型別操作,通常被稱為實用工具型別。
本章將介紹最流行的實用工具型別。
Partial
Partial
將物件中的所有屬性都變為可選。
示例
interface Point {
x: number;
y: number;
}
let pointPart: Partial<Point> = {}; // `Partial` 允許 x 和 y 是可選的
pointPart.x = 10;
自己動手試一試 »
必填
Required
將物件中的所有屬性都變為必需。
示例
interface Car {
make: string;
model: string;
mileage?: number;
}
let myCar: Required<Car> = {
make: 'Ford',
model: 'Focus',
mileage: 12000 // `Required` 強制要求定義 mileage
};
自己動手試一試 »
Record(記錄)
Record
是定義具有特定鍵型別和值型別的物件型別的快捷方式。
Record<string, number>
等同於 { [key: string]: number }
Omit
Omit
會從物件型別中移除指定的鍵。
示例
interface Person {
name: string;
age: number;
location?: string;
}
const bob: Omit<Person, 'age' | 'location'> = {
name: 'Bob'
// `Omit` 已從型別中移除了 age 和 location,因此無法在此處定義它們
};
自己動手試一試 »
Pick
Pick
會從物件型別中移除除指定鍵之外的所有鍵。
示例
interface Person {
name: string;
age: number;
location?: string;
}
const bob: Pick<Person, 'name'> = {
name: 'Bob'
// `Pick` 只保留了 name,因此 age 和 location 已從型別中移除,無法在此處定義它們
};
自己動手試一試 »
Exclude
Exclude
會從聯合型別中移除指定的型別。
示例
type Primitive = string | number | boolean
const value: Exclude<Primitive, string> = true; // 這裡不能使用 string,因為 Exclude 已將其從型別中移除。
自己動手試一試 »
ReturnType
ReturnType
提取函式型別的返回型別。
示例
type PointGenerator = () => { x: number; y: number; };
const point: ReturnType<PointGenerator> = {
x: 10,
y: 20
};
自己動手試一試 »
引數
Parameters
將函式型別的引數型別提取為陣列。
示例
type PointPrinter = (p: { x: number; y: number; }) => void;
const point: Parameters<PointPrinter>[0] = {
x: 10,
y: 20
};
自己動手試一試 »
只讀
Readonly
用於建立一個新型別,其中所有屬性都是隻讀的,這意味著一旦賦值,它們就不能被修改。
請注意,TypeScript 會在編譯時阻止此操作,但理論上由於它被編譯成 JavaScript,你仍然可以覆蓋只讀屬性。
示例
interface Person {
name: string;
age: number;
}
const person: Readonly<Person> = {
name: "Dylan",
age: 35,
};
person.name = 'Israel'; // prog.ts(11,8): error TS2540: 無法分配給 'name',因為它是一個只讀屬性。
自己動手試一試 »