I stumbled on your question because of the following Ramda pathOr type definition:
export function pathOr<T>(defaultValue: T, path: Path, obj: any): T;
The function can find a value deep inside an object, following a path.
The problem is that if you don't provide the generic type parameter T, Typescript will use the type from the defaultValue. This makes no sense when the object's content doesn't have the same type at that path.
The solution is complex and only works because there are two arguments. I don't think there's an easy answer to your question that works for all cases.
import {toPath} from 'lodash-es'
import {pathOr} from 'ramda'
// Aternative to lodash `get` where you have to provide a default value and a return type that includes the default value.
// Useful to avoid cases where the return type is inferred from the default value's type but does not fit with the object's content at the path.
export const getOr = <T = never, D extends T = T>(object: unknown, pathStr: string, defaultValue: D): T =>
pathOr(defaultValue, toPath(pathStr), object)
To be fair, ramda's path function and lodash's get function both try really hard to find the correct return type based on the object and the path, but I don't see how using a T type for both the default value and return value could be a good idea.
get
(of whatever API) returning{}
orany
and not what I expect it to, or how do I tell get what type my API returns. Always theget
has a type parameter that people do not see at first. With such a restriction it becomes mandatory and obviousU
would default to{}
, and you'd get an error when you try to access any properties on it, which would alert you to the problem.