'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")}
}


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1