Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...