Reputation: 11
I am trying to type this function in TypeScript and hitting a dead end every time. It’s complaining about using any
as a type of the passed in d object.
const current = (d: any): number => d.currentYear;
Basically, it is a function that takes in an object d
and returns .curentYear
property value out of it. The shape of the d
object may change and hence it can be any object. I tried to look into Generic Types and this is the closest I could find:
const getProperty = <T, K extends keyof T>(obj: T, key: K) => obj[key];
The downside is that I have to pass in the property during the function call:
getProperty(d, 'currentYear')
Is there any better way to type this function signature?
Upvotes: 0
Views: 198
Reputation: 98
if your 'd' may change, using extends keyword is better solution. in this way you guarantee that your d object will have a currentYear prop, no matter what.
interface HasCurrentYear = {
currentYear: number;
};
function current<T extends HasCurrentYear>(obj: T) {
return obj.currentYear;
}
so if you pass a object without cureentYear prop, you will give an error and the good point is that if you pass a object with currentYear and some other props it still works. also you can wtite it inline
function current<T extends { currentYear: number }>(obj: T) {
return obj.currentYear;
}
Upvotes: 0
Reputation: 817
Use an interface that has the property you need :
interface HasCurrentYear {
currentYear: number;
}
const current = (d: HasCurrentYear): number => d.currentYear;
Then, you can call current
with any object that has a currentYear
property :
current({currentYear:2021})
Upvotes: 1