• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

120
Vistas
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 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda