When I run the function below, I get this error: "Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'string | number'. Property '0' does not exist on type 'string | number"
I have seen index signature examples { [key: string]: number }
to solve similar issue, but I don't think it applies to this case. What would be the correct approach to solve this issue?
function getNames(namesAndAges: [ string, number ]): string[]{
return namesAndAges.map(val => (val[0]));
}
console.log(getNames([['Amir', 34], ['Betty', 17]]));
// expected result ['Amir', 'Betty']
CodePudding user response:
Your argument type is wrong.
function getNames(namesAndAges: [ string, number ])
means you would need to call it with an array containing a string and a number.
getNames(['a', 5])
You want an array of arrays instead. Type it as
function getNames(namesAndAges: Array<[ string, number ]>)