I have one object array with Types that is built by function with type Array<any> and would like to only use partial of key inside a forEach loop. what is more
precise, correct coding in typescript to provide a type?
what is right way to code in typescript, I can use forEach(xxx:any) but I would like to use like destructure object
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);
});
});
Your problem is caused by the way you're typing the
arraysparam ofcustomFunc: when it'sArray<any>(literally "array ofany") and the param is just returned, function's inferred return type also "array ofany".What you need is to inform what the array will contain, and you can do that either by specifying object's shape:
or via generics:
in this case, the function's return type will be inferred from the shape of the object passed into the function (at the spot the function is called).
The former approach is better when the function expects exact shape (because it e.g. does some manipulation with specific fields), while the latter is better when the function is doing something where exact shape is not expected (you can "combine" the approaches by making the
extendsparam more specific than just{}).