如何在字体脚本中定义ForEach下的类型? [英] how to define a type under forEach in typescript?

查看:15
本文介绍了如何在字体脚本中定义ForEach下的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PersonTypes对象数组,并且只想在forEach循环中使用Partial Of键。还有什么 打字稿中精确、正确的编码以提供一种类型?我可以做一些类似的事情 people.forEach((person: Pick<PersonTypes, 'name' | 'gender'>people.forEach((person: PersonTypes) =>{people.forEach((person: any) =>{ 在打字稿中编码的正确方法是什么

export type PersonTypes = {
  name: string;
  value: string;
  gender: boolean;
};
const people: PersonTypes[] = [
  {name: 'apl', value: 'apple', gender: true},
  {name: 'gal', value: 'google', gender: false},
]
people.forEach((person: Pick<PersonTypes, 'name' | 'gender'>) =>{
//people.forEach((person: PersonTypes) =>{
//people.forEach((person: any) =>{
  console.log(person.name);
  console.log(person.gender);
} )

推荐答案

您只需坚持:

people.forEach((person: PersonTypes) =>{


});

这是因为people数组中的每个对象都是PersonTypes类型,并且实际上不需要从该类型提取属性。

事实上,不需要将Person显式地键入为PersonTypes,因为People属于PersonTypes[]。TypeScrip将自动推断数组中的每个对象都是PersonTypes,因此这就足够了:

people.forEach((person) =>{


});  

或者,您也可以选择对参数进行结构调整,这将使您的函数更简洁、更干净。

people.forEach(({ name, gender }) =>{  
  console.log(name);
  console.log(gender);
});

这篇关于如何在字体脚本中定义ForEach下的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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