I am trying to write a simple getter for a value in an object with string keys or have some default of the same value type instead because I found myself needing to get values out of Maps many times. I assume this is a common pattern in Typescript. I am just looking for first level values no need to get nested data. It currently looks like this:
function getValueOrDefault<T>(
object: Record<string, T>,
path: keyof Record<string, T> & string,
orDefault: T
): T {
if (path in object && object[path] !== undefined) {
return object[path] as T;
} else {
return orDefault;
}
}
It seems like TypeScript infers in the object[path] that T could still be undefined even if I am already checking if object[path] !== undefined in the if block. Why is this happening? I have to cast with as T. Smells like a bad thing to do. Also can you get a better way to achieve what I am looking for?