typescript record
1
| Record<string | number | symbol, any>
|
构造一个对象类型,其属性key是Keys,属性value是Type。被用于映射一个类型的属性到另一个类型。
简单来说,TypeScript中的Record可以实现定义一个对象的 key 和 value 类型,Record 后面的泛型就是对象键和值的类型。
定义一个对象的key和value的类型。
1
| type A = Record<string, any>
|
那么结果就是
1 2 3
| const a:A = { "a": { a: 1 } }
|
我 key 用了 string 就合法了.
玩法还是比较多的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| type User = Record<"id" | "name" | "age", string>;
const s1 = Symbol("s1"); const s2 = Symbol("s2"); type SymbolMap = Record<typeof s1 | typeof s2, number>;
enum Status { Loading = "loading", Success = "success", Error = "error", } type StateData = Record<Status, string>;
const data: StateData = { [Status.Loading]: "加载中", [Status.Success]: "成功", [Status.Error]: "失败", };
type Action = "start" | "stop" | "pause"; type ActionHandlers = Record<Action, () => void>;
type RequiredUser = { id: number; name: string }; type PartialUser = Record<keyof RequiredUser, string | number | undefined>;
type ModuleConfig = Record<string, { enable: boolean; version: string }>;
type Flags<T> = Record<keyof T, boolean>; type User = { id: number; name: string; age: number }; type UserFlags = Flags<User>;
|
甚至,他还可以做嵌套
1
| type Matrix<T> = Record<string, Record<string, T>>;
|
https://juejin.cn/post/7040805750775480350
https://zhuanlan.zhihu.com/p/356662885