打字稿:“从不”类型上不存在“用户”属性

时间:2021-06-10 20:35:10

标签: typescript

我已经看到了大约 10 个关于此的问题,但它们似乎无法解释我的情况。 我有一个类型为 admin 的变量 PlayerType,我稍后设置,但出现错误:

Property 'user' does not exist on type 'never'

即使我清楚地检查了它是否已设置并且如果它存在于数据中就设置它...

示例代码 (codesandbox):

// My type
type PlayerType = {
  isAdmin: boolean;
  user: {
    name: string;
  };
};
// My code
let admin: PlayerType | null = null;

const players: PlayerType[] = [ // For demo, this info comes from server
    { isAdmin: false, user: { name: `John` } },
    { isAdmin: true, user: { name: `Jane` } }
];

players.map((player) => {
    if (player.isAdmin) {
      admin = player;
    }
    return player;
});

if (admin) {
    console.log(admin.user.name);
}

错误显示在控制台日志的 admin.user 中。

1 个答案:

答案 0 :(得分:2)

改用 .find,让 TypeScript 自动推断类型,即 PlayerType | undefined

const admin = players.find(player => player.isAdmin);
if (admin) {
    console.log(admin.user.name);
}

.map 仅用于当您需要通过转换另一个数组的每个元素来构造一个新数组时 - 这不是您在此处尝试执行的操作。

当值被构造和分配功能以及使用 const 时,让类型与 TypeScript 一起工作通常效果最好。

另一种选择是避免回调:

for (const player of players) {
  if (player.isAdmin) {
    admin = player;
  }
}
if (admin) {
  console.log(admin.user.name);
}

.map 以及一般回调的问题在于,TS 不知道是否或何时调用回调。最好的方法是使用返回您要查找的值的方法,而不是尝试按类型同时实现多个事情,TypeScropt 对此有问题。