类型'{}'不存在Typescript属性

时间:2020-06-08 14:34:33

标签: reactjs typescript

我的类型为User,可以是空对象或具有必填字段的对象。在函数getFirstName中,我检查object是否为空,然后返回其中一个字段。然后出现错误:“类型'{}'上不存在属性'firstName'”。为什么这样工作?

type User =
  | {
      firstName: string;
      age: number;
    }
  | {};

const getFirstName = (currentUser: User) => {
  if (!Object.keys(currentUser).length) {
    return "_";
  }
  return currentUser.firstName; //Property 'firstName' does not exist on type '{}'
};

export default function App() {
  const user: User = {
    firstName: "Bob",
    age: 14
  };

  const emptyUser = {};

  return (
    <div className="App">
      <h1>Hello {getFirstName(user)}</h1>
      <h1>Hello {getFirstName(emptyUser)}</h1>
    </div>
  );
}

CodeSandBox

2 个答案:

答案 0 :(得分:0)

1。建议Object.keys(currentUser).length <= 0而不是!Object.keys(currentUser).length

2。您需要强制转换联合类型,因为联合类型的多种类型中不存在属性firstName

type User =
  | {
      firstName: string;
      age: number;
    }
  | {};

const getFirstName = (currentUser: User) => {
  if (Object.keys(currentUser).length <= 0) {
    return "_";
  }
  return (currentUser as {
    firstName: string;
    age: number;
  }).firstName;
};

export default function App() {
  const user: User = {
    firstName: "Bob",
    age: 14
  };

  const emptyUser = {};

  return (
    <div className="App">
      <h1>Hello {getFirstName(user)}</h1>
      <h1>Hello {getFirstName(emptyUser)}</h1>
    </div>
  );
}

答案 1 :(得分:0)

一种更好的方法是从用户类型中删除空对象(这样您就可以充分利用打字稿的类型检查功能),并且当您遇到一个空对象(您知道它是用户类型)时,只需使用{{ 1}}关键字。

as