#Type predictions with classes

8 messages · Page 1 of 1 (latest)

plucky wraith
#

All examples for type predictions I found are for simple cases when I'm returning information about passed argument. Is it possible for myCache.has(x) and myCache.get(x) scenario?

https://www.typescriptlang.org/play/?#code/MYGwhgzhAECyCeBhMwAWBTaBvAsAKGmgAcBXAIxAEthoIAXAewCcwBzdALjjCIB56mlAHasANLTqCRAPmgBeaEPQB3bkQAUASgDc+fIVSR1Aa3TwuA4a01cyDBiHRgh2fYWhN0dEkxd1UlBAAdPTMbOhBhhAmZjpuAL56BNDsdDHmElLWFpJW0AA+0CRCACboAGbC6CWuyYSe3r7Q-oEhjCzsQanpccmJeP34wAxC9NDAKBjyiipwSJPoWrp4+JTl0OoTaBFR6gBEpvAAjHuamrWEw6N00ABuYCAkmApbGF1e+4cnvZcjEA4REAMVjqe6PCKMACqRCI6CYyAgizOy36QA

We don't have this on Map as well (this gives the same warning), I think I'm reaching too high...

const storage: Map<string, string> = new Map();

if (storage.has('test')) {
  storage.get('test').toUpperCase();
}
cedar rivetBOT
#

@plucky wraith Here's a shortened URL of your playground link! You can remove the full link from your message.

tedeusz#0

Preview:```ts
class MyCache {
public storage: Map<string, string> = new Map()

has(key: string): boolean {
return this.storage.has(key)
}

get(key: string): string | undefined {
return this.storage.get(key)
}
}

const cache = new MyCache()

if (cache.has("key1"))
...```

honest iron
#

there's no way to ensure the key hasn't been removed after checking

timid prairie
#

Yeah, there isn't really a good solution to this problem which is why the standard types don't solve it either.

#

Generally you do:

const value = cache.get("key1");
if(value !== undefined) {
    console.log(value.toUpperCase());
}
stark tinsel
#

^ That's the recommended way to go.

#

For Map<K, V>, .has(key) still has its place when you don't know if V can be undefined or not, so checking undefined after .get(key) might not be correct

#

In cases that you know V cannot be undefined, and in this case your cache's value also cannot be undefined, the way to go is to just call .get(key) and check for undefined afterwards.