1

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.

1 Answer 1

2

Use .find instead, and let TypeScript infer the type automatically, which will be PlayerType | undefined.

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

.map is only for when you need to construct a new array by transforming every element of another array - which isn't what you're trying to do here.

Getting type to work with TypeScript often works best when values are constructed and assigned functionally and with consts.

Another option is to avoid the callback:

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

The problem with .map, and with callbacks in general, is that TS doesn't know if or when the callback will be called. The best approach is to use a method that returns the value you're looking for, rather than to try to achieve multiple things at once type-wise, which TypeScropt has problems with.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.