Record Readonly 与 ReturnType
Record<K, V> 构造"键为 K、值为 V"的对象类型,是键值对字典的标准写法。Readonly<T> 把所有属性变只读。ReturnType<T> 与 Parameters<T> 从函数类型反向取出返回值与参数类型,接类型推断不下来的场子。
这组工具的卖点是完全自动:函数改了签名,ReturnType 的结果跟着变,绝不脱节。配置项字典、路由表这类场景,Record 比手写接口省心得多。
- Record
:键值对字典,键联合 + 值类型一手搞定 - Readonly
:全部属性只读;配合 ReadonlyArray 锁死数组 - ReturnType
/ Parameters :从函数类型反解返回值/参数
// Record:配置项字典
type Theme2 = 'light' | 'dark';
const themes: Record<Theme2, { bg: string; fg: string }> = {
light: { bg: '#fff', fg: '#333' },
dark: { bg: '#111', fg: '#eee' },
};
// themes.pink; // ❌ 键只能是 light / dark
// Readonly:赋值后锁死
const config: Readonly<{ port: number }> = { port: 8080 };
// config.port = 3000; // ❌ 只读属性不可赋值
// ReturnType / Parameters
function fetchUser(id: number): { name: string } {
return { name: '小明' };
}
type U = ReturnType<typeof fetchUser>; // { name: string }
type P = Parameters<typeof fetchUser>; // [id: number]
// 常见组合:组件 Props 直接继承函数返回值
type State = ReturnType<typeof createStore>;// Record / Readonly 只在编译期存在 const themes = { light: { bg: '#fff', fg: '#333' }, dark: { bg: '#111', fg: '#eee' }, }; function fetchUser(id) { return { name: '小明' }; } // 等价于手工写的 ReturnType const u = fetchUser(1); console.log(u.name); // 小明 console.log(themes.dark.bg); // #111




