Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

53
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")}
}
7 months 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

7 months 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 job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.