使用要点
- 每一步打印都带着自己的标签:
settings clicked。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。
核心语句
(<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? true : never;
type Handlers = { [K in Prefix]: () => void };
代码示例
type Route = "home" | "settings" | "billing";
// Intrinsic string manipulation types 在类型层变换字面量,且分布式作用于联合
type Label = Capitalize<Route>; // "Home" | "Settings" | "Billing"
type Prefix = `on${Capitalize<Route>}Click`; // "onHomeClick" | ...
type Handlers = { [K in Prefix]: () => void };
const handlers: Handlers = {
onHomeClick: () => console.log("home clicked"),
onSettingsClick: () => console.log("settings clicked"),
onBillingClick: () => console.log("billing clicked"),
};
// 拼错事件名编译报错:Handlers 上不存在 onhomeClick
handlers.onSettingsClick();
type ExpectEqual<T, U> =
(<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? true : never;
const a: ExpectEqual<Label, "Home" | "Settings" | "Billing"> = true;
console.log(a);