Issue
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?
Solution
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]]);
Answered By - b3hr4d
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.