TypeScript:如何从表格行类型生成API响应的数组对象类型?
如何通过表格行类型推导API响应的类型
我有一个API的响应结构如下:
{ age: [1,2,3], name: ['Alan', 'Bob', 'Charlie'], fruit: ['Apple', 'Banana', 'Cherry'] }
我已经实现了转换函数,能把它转成表格所需的数组结构:
[ {age: 1, name: 'Alan', fruit: 'Apple'}, {age: 2, name: 'Bob', fruit: 'Banana'}, {age: 3, name: 'Charlie', fruit: 'Cherry'}, ]
表格行的类型定义是:
interface TableRowProps { age: number name: string fruit: string } type TableDataProps = Array<TableRowProps>
现在我想反过来,通过TableRowProps推导出API响应的类型,最终要得到:
interface ApiResponseProps { age: Array<number> name: Array<string> fruit: Array<string> }
我尝试了下面的代码,但无法正常工作:
type ApiResponseProps<Type> = { [Property in keyof Type]: Array<Property> } const myvar: NewProps<TableRowProps> = [...array-based data]
需要正确的TypeScript类型转换方法。
正确的类型转换写法
你需要用Type[Property]获取属性对应的值类型,而不是直接使用Property(它是属性名的字面量类型,不是属性值的类型)。正确的工具类型写法如下:
type ApiResponseProps<T> = { [K in keyof T]: Array<T[K]> }
使用时直接传入TableRowProps即可:
// 自动推导得到目标API响应类型 type DerivedApiResponse = ApiResponseProps<TableRowProps> // 验证类型是否符合预期 const apiResponse: DerivedApiResponse = { age: [1,2,3], name: ['Alan', 'Bob', 'Charlie'], fruit: ['Apple', 'Banana', 'Cherry'] }
错误原因说明
你之前的代码里用了Array<Property>,这里的Property是'age' | 'name' | 'fruit'这类字符串字面量类型,而不是属性值的number或string类型,所以类型完全不匹配,自然无法正常工作。
内容的提问来源于stack exchange,提问作者foreverAnIntern
相关产品推荐
相关产品推荐

