The least crazy way to approach this is to just call get()
and then use the return value of undefined
to indicate that the entry does not exist. If your map value type could possibly be undefined
, that would be a problem, but undefined
is not assignable to any[]
, so it's a reasonable way to distinguish presence from absence:
const dictionary = new Map<string, any[]>()
function addValueToExistingEntry(key: string, value: any) {
const existingEntry = dictionary.get(key);
if (existingEntry !== undefined) {
existingEntry.push(value)
}
}
If you want to start using type guard functions to narrow the map to a type with a definite value at the given key, you need to use lots of generics and specifically have the key be of a type narrower than string
, like a generic constrained to string
or like a string literal type. Like this:
function dictionaryHasKey<
M extends Map<string, any>,
K extends string
>(dict: M, key: K): dict is { get(k: K): M extends Map<any, infer V> ? V : never } & M {
return dict.has(key);
}
And then your original code will work:
function hmmAddValueToExistingEntry<K extends string>(key: K, value: any) {
if (dictionaryHasKey(dictionary, key)) {
const existingEntry = dictionary.get(key);
existingEntry.push(value);
}
}
But that's a lot of work and advanced type-system hoop jumping compared to just checking existingEntry
for being undefined
.
Okay, hope that helps; good luck!
Playground link to code
key
is just of typestring
then there's nothing you can do since the compiler won't be able to remember that you're using the same key in thedictionaryHasEntry()
call and in theget()
call. You don't want the compiler to think that allstring
keys have values in the map. You'd need to narrow downkey
fromstring
to some string literal type for that to begin to work. Why not just callget()
and check it forundefined
?