【问题标题】:how to provide type from a object with type any in destructure way如何以解构方式从具有任何类型的对象提供类型
【发布时间】:2020-07-27 09:29:10
【问题描述】:

我有一个类型为 Array<any> 的函数构建的对象数组,并且只想在 forEach 循环中使用部分键。更 打字稿中精确、正确的编码以提供类型?

什么是在打字稿中编码的正确方法,我可以使用forEach(xxx:any),但我想使用像解构对象一样

export function customFunc(...arrays: Array<any>){
  return arrays
}
export type PersonTypes = {
  name: string;
  value: string;
  gender: boolean;
};
const people = [
  ...customFunc([{name: 'apl', value: 'apple', gender: true},
  {name: 'gal', value: 'google', gender: false},])
]
people.forEach(person => {
  person.forEach(({name, gender})=>{ 
### how to provide type with destructure object with error Binding element 'name' implicitly has an 'any' type
    console.log(name);
    console.log(gender);
  });
});

【问题讨论】:

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


    【解决方案1】:

    您的问题是由您输入customFuncarrays 参数的方式引起的:当它是Array&lt;any&gt;(字面意思是“any 的数组”)并且该参数刚刚返回时,函数的推断返回类型还有“any 的数组”。

    你需要知道数组将包含什么,你可以通过指定对象的形状来做到这一点:

    export function customFunc(...arrays: Array<{ name: string; value: string }>){
      return arrays
    }
    

    或通过泛型:

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

    在这种情况下,函数的返回类型将从传递给函数的对象的形状中推断出来(在函数被调用的地方)。

    当函数需要精确的形状时,前一种方法更好(因为它例如对特定字段进行一些操作),而当函数正在做一些不期望精确形状的事情时,后者更好(你可以“组合”通过使extends 参数比{} 更具体的方法。

    【讨论】:

      猜你喜欢
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 2014-06-03
      • 2016-04-07
      • 2016-12-29
      • 2017-05-06
      • 1970-01-01
      相关资源
      最近更新 更多