如何创建myCastType泛型,实现字符串联合类型到指定对象的转换?
解决方案
你需要的泛型可以直接通过TypeScript内置的Record工具类型实现,甚至无需自定义新泛型。如果一定要使用myCastType这个名称,也可以基于Record简单封装。
直接使用Record(推荐)
type myType = 'name' | 'age' | 'family' | 'other'; // 直接用Record<联合类型, 值类型>定义对象类型 const myObject: Record<myType, string> = { name: 'string', age: 'string', family: 'string', other: 'string', };
自定义myCastType泛型
如果你希望保留myCastType的命名,只需对Record做一层封装:
// 定义泛型,约束泛型参数为合法的对象键类型 type myCastType<T extends string | number | symbol> = Record<T, string>; type myType = 'name' | 'age' | 'family' | 'other'; const myObject: myCastType<myType> = { name: 'string', age: 'string', family: 'string', other: 'string', };
原理说明
Record<K, T>是TypeScript内置的工具类型,作用是构造一个对象类型:
- 所有属性的键必须来自类型
K(这里就是你的字符串联合类型myType) - 每个属性的值类型统一为
T(这里指定为string)
当你省略联合类型中的任意属性时,TypeScript会直接抛出类型错误,强制要求你声明所有属性,完全符合你的动态属性需求。
内容的提问来源于stack exchange,提问作者Gianfrancesco Aurecchia
相关产品推荐
相关产品推荐

