Home > OS >  How to change the type of an object property on an extended interface?
How to change the type of an object property on an extended interface?

Time:12-14

Example:

interface Foo {
  myProp: string
  myObjectProp: {
    objProp1: string
    objProp2: number
  }
}

interface Bar extends Foo {
  myObjectProp: {
    objProp2: string // Error: Interface 'Bar' incorrectly extends interface 'Foo'
  }
}

How do I change the type of objProp2 without having to completely redeclare the myObjectProp on the extended interface?

CodePudding user response:

You can use generic types with default values.

interface Foo<T = ShapeA> {
  myProp: string
  myObjectProp: T
}

interface ShapeA {
  objProp1: string
  objProp2: number
}

interface ShapeB {
  objProp2: string
}

interface Bar extends Foo<ShapeB> {
  myObjectProp: {
    objProp2: string
  }
}

TSPlayground

  • Related