I've seen about 10 questions about this, but they don't seem to explain my situation.
I have a variable admin with a type PlayerType that I set later, but get the error:
Property 'user' does not exist on type 'never'
Even though I clearly check if it is set and do set it if it exists in the data...
Sample code (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);
}
The error shows up on the admin.user of the console log.