集合类型
array、tuple、object、enum、hybrid-types。
30 分钟
集合类型
数组、元组、对象字面量、枚举与混合类型是日常建模的主力。本课在 typescript-essentials 基础上深入 array、tuple、object、enum、hybrid-types,为 API 响应与表单 DTO 建立精确结构——这在 nestjs-essentials 的 Entity/DTO 与 nextjs-essentials 的 fetch 数据类型中随处可见。
学习目标
- 区分
T[]与只读元组、可变长度元组 - 使用
as const与字面量联合替代部分 enum - 建模「对象 + 可调用」的混合类型
数组与元组
// 同质数组
type LessonSlug = string;
const slugs: LessonSlug[] = ["tsa-intro", "tsa-primitives"];
// 固定长度元组:位置语义
type Point2D = [x: number, y: number];
const origin: Point2D = [0, 0];
// 可变元组 rest
type HeadTail = [string, ...number[]];
const row: HeadTail = ["track", 1, 2, 3];
// 只读元组
type RGB = readonly [number, number, number];
object 与 Record
// object:非原始类型的对象
function logObj(obj: object): void {
console.log(JSON.stringify(obj));
}
// Record:键值映射
type TrackMap = Record<string, { title: string; level: string }>;
const tracks: TrackMap = {
"typescript-advanced-essentials": {
title: "TypeScript 进阶",
level: "intermediate",
},
};
enum 与 const 对象
// 数字 enum(注意反向映射)
enum Order {
Asc,
Desc,
}
// 推荐:const 对象 + 字面量联合
const LessonStatus = {
Draft: "draft",
Published: "published",
} as const;
type LessonStatus = (typeof LessonStatus)[keyof typeof LessonStatus];
// "draft" | "published"
混合类型(Hybrid Types)
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
const fn = ((start: number) => String(start)) as Counter;
fn.interval = 1000;
fn.reset = () => {};
return fn;
}
练习
- 用元组类型描述
[slug, title, durationMinutes] - 将 platform 中某 enum 改写为
as const+ 联合类型 - 为带
call签名的工具函数设计 hybrid interface