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

168
Views
Typescript function that takes extended interface as input

I have an interface (in the example is called "Example") that includes a function type ("exampleFunction"), but this function takes a super class as an input parameter, and typescript reports an error stating that i can't use subtypes as input because they have some properties that are not present in the super type.

Here is an example:

interface SuperType {
   propertyA: string
}

interface SubTypeA extends SuperType {
   subPropertyA: number
}

interface SubTypeB extends SuperType {
   subPropertyB: number
}

interface Example {
   exampleFunction: (input: SuperType) => void
}

i have a problem if i write:

const example: Example = {
   exampleFunction: (input: SubTypeA) => {console.log("nothing")}
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is easier to spot if you make your function use the SubTypeA only property.

const example: Example = {
   exampleFunction: (input: SubTypeA) => {console.log(input.subPropertyA.toFixed())}
}

The function itself is perfectly valid (it accepts a SubTypeA argument and accesses one of the properties. However, the Example type can only guarantee that a SuperType is passed in. So the other unique properties of SubTypeA can't be guaranteed to exist.

For example:

const superType: SuperType = { propertyA: 'foo' }
example.exampleFunction(superType)
// valid call, but crashes because `subPropertyA` doesn't exist

Perhaps one fix is to make your function handle a SuperType or a SubTypeA?

const example: Example = {
   exampleFunction: (input: SuperType | SubTypeA) => {
       if ('subPropertyA' in input) {
            console.log(input.subPropertyA.toFixed())   
       }
    }
}

const superType: SuperType = { propertyA: 'foo' }
example.exampleFunction(superType) // works

const subTypeA: SubTypeA = { propertyA: 'foo', subPropertyA: 123 }
example.exampleFunction(subTypeA) // works

Playground

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!