0

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?

1
  • not sure why sometimes people on stackoverflow, give down vote without telling the reason. It's really unfair. Commented May 30, 2021 at 16:30

2 Answers 2

1

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})
Sign up to request clarification or add additional context in comments.

Comments

0

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;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.