如何使用 tslint 映射数组和 return 对象。 (语法糖)

How to map on a array and return a object with tslint. (syntactic sugar)

这是一个纯粹的语法糖问题。

如何使用 map 和 return 遍历一个新对象的数组而不让 TSLint 说:

This arrow function body can be simplified by omitting the curly braces and the keyword 'return', and wrapping the object literal in parentheses.

例如对象用户:

class User {
    constructor(
        public id: number, 
        public first_name: string, 
        public last_name: string, 
        public gender: Date, 
        public location: number, 
    )
}

当我这样做时:

const simple_users = users.map(u => { return { name: u.name, id: u.id} });

然后会发生这种情况:

[tslint] This arrow function body can be simplified by omitting the curly braces and the
keyword 'return', and wrapping the object literal in parentheses. (arrow-return-shorthand)

我想保留 tslint 规则 arrow-return-shorthand

只需将您的对象包裹在 ()(括号)内并删除 functionreturn 语句。 shorthand在下面。

const simple_users = users.map(u => ({ name: u.name, id: u.id}));

进一步destructuring版本会更短。

const simple_users = users.map(({name, id}) => ({ name, id}));