打字稿参数-对象的通用数组和对象键的数组(部分) [英] Typescript parameters - a generic array of objects and array of object's keys (partial)

查看:121
本文介绍了打字稿参数-对象的通用数组和对象键的数组(部分)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有一个接受对象数组和一些对象键数组的方法.该方法将返回一个对象值数组,但仅包含选定键的数组.

I want to have a method that accepts an array of objects and an array of some of the objects keys. The method will return an array of arrays of object values but only of the selected keys.

数据:

[
  {"firstName": "Jane", "lastName": "Doe"},
  {"firstName": "John", "lastName": "Doe"}
]

字段:

["firstName"]

结果:

[["Jane"], ["John"]]

现在,我有一个可以提供所需结果的函数,但是我不确定如何更好地处理类型.

By now I have a function that provides desired outcome but I am not sure how to handle the types better.

mapToCsvData: (data: { [key: string]: any }[], fields: string[]) => {
  return data.map((item: any) => {
    return fields.map(field => item[field]);
  });
}

我尝试了下一个代码段的一些变体,但出现错误.

I have tried some variations of the next snippet but I get an error.

mapToCsvData: <T extends object>(data: T[], fields: keyof T[]) => {

Property 'map' does not exist on type 'number'.

推荐答案

您将需要一个额外的type参数来捕获传入的键的实际元组.您可以将它们映射为中的相应属性类型.T .一切都很顺利:

You will need an extra type parameter to capture the actual tuple of keys being passed in. You can them map this tuple to the corresponding property types in T. It all works out very nicely:

type MapKeyTupleToProps<T, P extends [keyof T] | Array<keyof T>> = {
    [K in keyof P]: P[K] extends keyof T ? T[P[K]] : never
}
const m = {
    mapToCsvData: <T, P extends [keyof T] | Array<keyof T>>(data: T[], fields: P): MapKeyTupleToProps<T, P> => {
        return data.map((item: any) => {
            return fields.map(field => item[field]);
        }) as any;
    }
}

const data = [
    {"firstName": "Jane", "lastName": "Doe", age: 0},
    {"firstName": "John", "lastName": "Doe", age: 0}
]

let r = m.mapToCsvData(data, ["firstName", "lastName"]) // [string, string]
let r2 = m.mapToCsvData(data, ["firstName", "age"]) //[string, number]

这篇关于打字稿参数-对象的通用数组和对象键的数组(部分)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆