I am new to TS and struggling to type the following arrow function:
const mapLikeGet = (obj, key) => {
if (Object.prototype.hasOwnProperty.call(obj, key))
return obj[key]
}
CodePudding user response:
Contrary to the other answers, and considering that the person asking is a beginner, I think this should be as simple as possible:
const mapLikeGet = (obj : any, key : string) => {
if (Object.prototype.hasOwnProperty.call(obj, key))
return obj[key]
}
The fact you are using Object.prototype.hasOwnProperty.call
means that you are not even assuming that obj
inherits from Object
, hence I see this as a perfect case for using the any
type.
The key
, on the other hand, is obviously a string.
CodePudding user response:
You can use generics and set the first variable must be an object and the second variable the k of the object and the result will be the O[key]
or undefined
.
const mapLikeGet = <O extends Object, K extends keyof O>(obj: O, key: K): O[K] | undefined => {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return obj[key];
}
return undefined;
}
// foo
const foo = {
one: 1,
two: "",
};
const oneVal = mapLikeGet(foo, "one");
// oneVal => number | undefined
In Typescript 4.9
you could use the in
operator. (See: Announcing TypeScript 4.9):
const mapLikeGet = <O extends Object, K extends keyof O>(obj: O, key: ): O[K] | undefined => {
if (key in obj) {
return obj[key];
}
return undefined;
}
CodePudding user response:
You can type it using generics and keyof
:
const mapLikeGet = <T,>(obj: T, key: keyof T) => {
if (Object.prototype.hasOwnProperty.call(obj, key))
return obj[key]
return undefined;
}
const foo = mapLikeGet({ foo: "bar"}, "foo");
// ^? const foo: string | undefined