0

I am using strict mode for the following code. Trying to assign an object value from a Map. It is granted that the value I am getting from the Map isn't undefined but strict mode giving the following error Type A[]|undefined isn't assignable to type A[]. How can I pass this compiler issue?

let key = "foo"
leaderboardRecords: A[] = [];
leaderboardRecordsbyRegion: Map<string, A[]> = new Map<string, A[]>();
if (!leaderboardRecordsbyRegion.has(key)) {
        leaderboardRecordsbyRegion.set(key, fetchData());
    }
leaderboardRecords = leaderboardRecordsbyRegion.get(key);
5
  • There is highly likely chance that the return type of function fetchData() would be A[]|undefined. So error says that types are not matching. Simple Commented Oct 9, 2022 at 5:30
  • You should add minimal reproducible code, so that people can understand your problem clearly. Commented Oct 9, 2022 at 5:33
  • 1
    Use the Non-null assertion operator, leaderboardRecords = leaderboardRecordsbyRegion.get(key)!; Commented Oct 9, 2022 at 5:44
  • @DecPK fetchData() returns a promise<A[]> Commented Oct 9, 2022 at 6:14
  • @PhilopateerNabil can you add your full code where this problem is reproducible Commented Oct 9, 2022 at 6:26

1 Answer 1

0

This is how I solved it in the end. I added or empty array to pass the compiler.

leaderboardRecords = leaderboardRecordsbyRegion.get(key) || [];
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.