map
遍历一个数组并返回一个新对象,而无需TSLint说:可以通过省略花括号和关键字“ return”,并将对象文字括在括号中来简化此箭头功能主体。
例如,对象用户:
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
。
答案 0 :(得分:7)
只需将对象包装在()
(括号)内,然后删除function
和return
语句。简写在下面。
const simple_users = users.map(u => ({ name: u.name, id: u.id}));
进一步destructuring
版本会更短。
const simple_users = users.map(({name, id}) => ({ name, id}));