0

I have to write a function that takes an array of tuples, each tuple consists of a name and an age. The function should return only the names.

So I wrote it like this:

type someTuple = [string, number]

function names(namesAndAges: someTuple[]) {
  let allNames: string[]
  allNames.push(namesAndAges.forEach( nameAndAge => nameAndAge[0]))
  
  return allNames
}

When I call it with this:

names([['Amir', 34], ['Betty', 17]]);

I get this error:

type error: type error: Variable 'allNames' is used before being assigned.

Can anyone point what is wrong with this code?

2 Answers 2

1

You didn't declare allNames to be an array, so change it to this:

let allNames: string[] = []

If you want to get all name in an array your function should be like this:

type someTuple = [string, number]

function names(namesAndAges: someTuple[]) {
  let allNames: string[] = []
  namesAndAges.forEach( nameAndAge => 
    allNames.push(nameAndAge[0])
  )
  return allNames
}

names([['Amir', 34], ['Betty', 17]]);

Playground

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I was forgetting this. Now I'm getting this error: type error: Argument of type 'void' is not assignable to parameter of type 'string'
Perfect! Thank you!
Happy to help you :)
0

You can also use .map here for a better code readability

function names(namesAndAges: [string, number][]): string[] {
  return namesAndAges.map(nameAndAge => nameAndAge[0]);
}

names([['Amir', 34], ['Betty', 17]]);

TS Playground

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.