Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

341
Views
TypeScript: Allow types as parameter of function that contain certain keys

Let´s assume I have two interfaces.

interface AppleReport {
    name: string,
    color: string,
    age: string
}

interface BananaReport {
    name: string,
    color: string,
    amount: number,
}

Now I define a function. I want this function to take every type that has a name key and a color key.

cosnt doSth = (value: **TODO**) => {
    // do sth with *value* that contains *name* and *color*
}

I know, that I could create an interface

interface dummyInterface {
    name: string,
    color: string,
}

and let the AppleReport and BananaReport extend this, but I would like to do all of the logic in the function type definiton.

Any ideas?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could do

cosnt doSth = (value: { name : string, color : string } ) => {
    // do sth with *value* that contains *name* and *color*
}

but This looks messy and would recommend going with the way you do not want to and create an interface and then extend the other 2 interfaces from it.

or if you dont want to extends the other interfaces you can just use the interface type as the type to pass in and not extend. It will still work as long as the members exist.

interface NameAndColor {
  name: string,
  color: string,
}

interface AppleReport {
  name: string,
  color: string,
  age: string
}

interface BananaReport {
  name: string,
  color: string,
  amount: number,
}

const doSth = (value: NameAndColor) => {
  // do sth with *value* that contains *name* and *color*
}

let obj = { name : "myName", color : "myColor"};
doSth( obj );

But really the best way is to have your interfaces extend in my opinion.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!