TypeError:无法解构“未定义”的属性“名称”,因为未定义

时间:2020-07-25 12:10:59

标签: reactjs ecmascript-6

enter image description here在一个新的reactjs项目中,我有以下基本代码:

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

给我这个错误:

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

这是什么意思?

我在上方没有同时定义用户及其名称吗?为什么说我不是?

意图是:

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

1 个答案:

答案 0 :(得分:0)

感谢大家的帮助! 事实证明,一旦添加here,一切正常就可以了

工作代码的最终版本是:

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'