Looking to create a simple getter for retrieving a value from an object with string keys, or returning a default value of the same type when necessary. This situation arises frequently when working with Maps in Typescript. The main focus is on accessing top-level values without delving into nested data structures. Here is the current implementation:
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;
}
}
The issue here is that TypeScript continues to infer that `T` could potentially be `undefined`, even after explicitly checking `if object[path] !== undefined`. This leads to the need for casting with `as T`, which is not optimal. Is there a better approach to achieving the desired behavior?