打字稿数组映射返回对象

时间:2017-12-11 14:37:56

标签: typescript

我有以下代码。

array.map(val => { return {
  key1: val.key1,
  key2: val.key2
}});

有没有办法将代码减少到这样的程度?

array.map(val => {
  key1: val.key1,
  key2: val.key2
});

2 个答案:

答案 0 :(得分:28)

如果将其放在括号中,编译器会将其视为对象文字而不是代码块:

#include <cstdio>
#include <iostream>
#include <cuda_runtime.h>
#include <cublas_v2.h>
#include <cstdlib>

using namespace std;

void get_vec_random(float* a, int count)
{
    for(int i=0; i<count; i++)
        a[i] = rand() / float(RAND_MAX);    
}

void get_mat_random(float* a, int rows, int cols)
{
    get_vec_random(a, rows * cols);
}

int main(int argc, char** argv)
{
    int rows = 10, cols = 10;

    cublasHandle_t handle;
    cublasCreate(&handle);


    float *a, *x, *y;
    int NUM_VEC = 8;
    y = (float*)malloc(sizeof(float) * rows * NUM_VEC);
    a = (float*)malloc(sizeof(float) * rows * cols);
    x = (float*)malloc(sizeof(float) * cols * NUM_VEC);
    get_mat_random(a, rows, cols);
    get_vec_random(x, cols * NUM_VEC);

    float *d_a = 0;
    float *d_x = 0;
    float *d_y = 0;

    cudaMalloc((void **)&d_a, rows * cols * sizeof(float));
    cudaMalloc((void **)&d_x, cols * NUM_VEC * sizeof(float));
    cudaMalloc((void **)&d_y, rows * NUM_VEC * sizeof(float));


    cublasSetVector(rows * cols, sizeof(float), a, 1, d_a, 1);
    cublasSetVector(NUM_VEC * cols, sizeof(float), x, 1, d_x, 1);
    cublasSetVector(NUM_VEC * rows, sizeof(float), y, 1, d_y, 1);

    float alpha = 1.0f, beta = 1.0f;

    cublasSetPointerMode(handle, CUBLAS_POINTER_MODE_HOST);
    for (int i = 0; i < NUM_VEC; i++) 
    {
        cublasSgemv(handle, 
                    CUBLAS_OP_T, 
                    cols, 
                    rows, 
                    &alpha, 
                    d_a, 
                    rows, 
                    d_x + i * cols, 
                    1, 
                    &beta, 
                    d_y + i * rows, 
                    1);
    }
    return 0;
}

如果你有一个对象文字的接口(但不是类型安全的),那么类型断言也有效:

array.map(val => ({
  key1: val.key1,
  key2: val.key2
}));

答案 1 :(得分:6)

作为@Titian Cernicova-Dragomir的答案above的更新,值得一提的是as operator(用于类型声明),在处理React的TSX(JSX)文件时特别有用,等效于{ {1}}语法:

<Type>

之所以引入它,是因为尖括号语法(interface IKeys { key1: string; key2: string } // notice the parentheses, to avoid confusion with a block scope array.map(val => ({ key1: val.key1, key2: val.key2 } as IKeys)); )保留用于组件/ JSX元素。