Divya offered to conduct a mock interview with me. She asked me to create a MemTable, which is apparently a type of KV store in which, at some interval or after some threshhold of KVs, KV store is “flushed” and saved to the disk to preserve memory.
I was able to implement it in about 30 minutes and I think it went really well! Here was the finished result, and the feedback she gave me at the end.
One of the bits of critical feedback was that I didn’t know why typescript throws a type error in this function:
I used the ! non-null assertion operator to ignore the warning, but didn’t have an especially deep understanding of this pattern, or perhaps anti-pattern
Looking further into it, it looks like the warning exists because the get method of a Map in TypeScript returns T | undefined, where T is the type of the values stored in the map. In this case, it’s number | undefined.
This is the intellisense message I get in VScode:
Type 'number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.ts
Apparently Typescript doesn’t really have a way to see that the above line ensures that the function won’t return undefined.
My use of the non-null assertion operator is one way to get around this.
However, there are other ways that might be better.
I can use a type assertion:
return this.table.get(key) as number
This essentially does the same thing as a non-null assertion operator, as far as I can tell, as it’s overriding Typescript’s type system and saying ‘trust me, this is a number.’
I can use the nullish coalescence operator:
return this.table.get(key) ?? -1
I like this option the best. It allows me to handle both lines with just one line, and take advantage the the way map.get can return undefined in the way I think it was intended to be used. It’s completely typesafe, which is dope.
It’s important to be able to tell the nullish coalescence operator (??) from the logical OR operator (||).
x ?? y returns y only if x is null or undefined.
x || y would return y for any falsy value of x, including 0 and ”
They can both be useful, but could cause serious bugs if one is substituted for another.