【问题标题】:how to define a type under forEach in typescript?如何在 typescript 的 forEach 下定义一个类型?
【发布时间】:2020-07-27 07:20:03
【问题描述】:

我有一个 PersonTypes 对象数组,并且希望只在 forEach 循环中使用部分键。更 打字稿中精确、正确的编码以提供类型?我可以做类似的事情 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);
} )

【问题讨论】:

  • "keep away me from bake on PR"究竟是什么意思?为什么不能只使用推断类型PersonTypes,即只写.forEach(person =&gt; { ... });

标签: typescript typescript-typings typescript2.0 typescript1.8


【解决方案1】:

你应该坚持:

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


});

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

事实上,没有必要将 person 显式键入为 PersonTypes,因为 people 是 PersonTypes[]。 TypeScript 会自动推断数组中的每个对象都是PersonTypes,所以这就足够了:

people.forEach((person) =>{


});  

或者,您可以选择解构参数,这将使您的函数更加简洁明了。

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

【讨论】:

  • Binding element 'name' implicitly has an 'any' type我的解构方式有错误
  • @jacobcan118 向我们展示你是如何解构的。使用 people.forEach(({ name, gender }) =&gt; ... ); 对我有用:typescriptlang.org/play/#code/…
  • @Terry 我认为问题出在我的 customZip 函数上,我无法真正更改 typescriptlang.org/play/?ssl=18&ssc=1&pln=18&pc=4# 如何解决?
  • @jacobcan118 请更新您的问题:游乐场链接不起作用
  • @jacobcan118 请更新您的问题:将链接粘贴到 cmets 中对将来的其他人没有帮助,因为实际代码与您的原始问题相差太大(没有提到自定义压缩函数)
【解决方案2】:

根据您提供的附加代码,customZip 函数的返回类型为 any,这当然会导致稍后出现问题,因为该数组的类型为 any 而不是推断的 PersonType[]

export function customZip(...arrays: Array<any>){
  return arrays
}

要解决这个问题,只需使用generics in TypeScript 的概念就可以了,它允许编译器自行推断数组的类型:

export function customZip<T>(...arrays: Array<T>){
  return arrays
}

See proof-of-concept example.

你可以选择提供一个类型,或者简单地让 TypeScript 自己推断。在这一点上并不重要:两者都会正确编译:

// You let TypeScript do the inferring by itself
const people = [
  ...customZip([{name: 'apl', value: 'apple', gender: true},
  {name: 'gal', value: 'google', gender: false},])
];

...或...

// Your manually inform TypeScript what the type of an array member returned from customZip looks like
const people = [
  ...customZip<PersonTypes[]>([{name: 'apl', value: 'apple', gender: true},
  {name: 'gal', value: 'google', gender: false},])
];

【讨论】:

    猜你喜欢
    • 2019-08-22
    • 2020-01-23
    • 2018-02-23
    • 1970-01-01
    • 2020-08-05
    • 2019-11-04
    • 1970-01-01
    • 2020-12-15
    • 2021-08-04
    相关资源
    最近更新 更多