I have created a function called get(o, key)
, which is designed to work with any Object that meets the criteria of the { get: (key: K) => R }
interface.
Furthermore, I am interested in restricting the result variable R
to not allow it to be undefined
. How can this restriction be implemented?
Is there a way to modify the example provided below so that it does not compile due to the fact that the method
Params::get(key: string): number | undefined
may potentially return undefined
?
function get<K, R>(o: { get: (key: K) => R }, key: K): R {
return o.get(key);
}
class Params {
constructor(public values: { [key: string]: number }) { }
get(key: string): number | undefined {
return this.values[key]
}
}
const params = new Params({ a: 10 });
console.log(get(params, "a"))