Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Correct way to map through tuple type parameter

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']

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ]>)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading