繁体   English   中英

Typescript:“从不”类型上不存在属性“用户”

[英]Typescript: Property 'user' does not exist on type 'never'

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

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

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

示例代码(代码):

// 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上。

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

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

.map仅适用于当您需要通过转换另一个数组的每个元素来构造新数组时 - 这不是您在这里想要做的。

让类型与 TypeScript 一起使用通常在功能上构造和分配以及使用const时效果最佳。

另一种选择是避免回调:

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

.map和一般回调的问题在于 TS 不知道是否或何时调用回调。 最好的方法是使用返回您正在寻找的值的方法,而不是尝试在类型方面一次实现多个目标,TypeScopt 存在问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM