My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist.
async get(key: string, def_value?: any): Promise<any> {
const v = await redisInstance.get(key);
return v ? v : def_value;
}
Would it be possible to specify proper types for this method instead of using 'any'?
I had the idea to modify the method signature like this:
async get<T>(key: string, def_value?: T): Promise<T>
This way, the type would be inferred from def_value, but then def_value couldn't be optional. Is there a way to make def_value
both optional (undefined) and of type T? Can TypeScript detect if a default value was provided or not? If a default value is provided, infer T from that value; if no default value is provided, prompt for a type, like
get<string[]>("my_key");
?