0

enter image description hereIn a new reactjs project I have this basic code:

type User = {
  name: ?string,
  age: ?string,
};
const getUserName = ({name,age,}: User): ?string => name;

giving me this error:

TypeError: Cannot destructure property 'name' of 'undefined' as it is undefined.

What does this mean?

Am I not defining both User and its name just above?! Why is it saying I'm not?

Intention is:

const someUser = { name: "John", age: "12" }
const userName = getUserName(someUser)
console.log(userName)// should output 'John'
19
  • 1
    You need to pass an object of shape {name, age} in getUserName currently you are not passing any params Commented Jul 25, 2020 at 12:13
  • thank you, just fyi I'm a backend engineer so all this react kung-fu is new to me :), i thought i was passing an arg here '({name,age,}: User)' what's that then? Commented Jul 25, 2020 at 12:15
  • @jakstack you're declaring a function, the stuff between the () is the arguments for your arrow function. Here you're destructuring the arguments of an input object, which has the type of User. Commented Jul 25, 2020 at 12:24
  • Here you are defining the parameters the function accepts in your case it is an object of the shape {name, age} and you are destructuring that object. You want to use this function as getUserName({ name: "John", age: 12 }) Commented Jul 25, 2020 at 12:25
  • 2
    Is this TypeScript, or Flow? Are you getting a runtime error or a compile time type error? Commented Jul 25, 2020 at 12:52

2 Answers 2

2

Add flow:

npm install --save flow-bin

or

yarn add flow-bin.

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

1 Comment

Please add why this solves the problem.
0

Thank you everyone for the good help! It turned out to be missing flow once added here it all worked fine

finale version of the working code is:

type User = {
  name: ?string,
  age: ?string,
};
const getUserName = ({name,age,}: User): ?string => name;

const someUser = { name: "John", age: "12" }
const userName = getUserName(someUser)
console.log(userName)// should output 'John'

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.