VaioWay
VaioWay

Reputation: 402

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

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?

Upvotes: 1

Views: 135

Answers (1)

Salmin Skenderovic
Salmin Skenderovic

Reputation: 1720

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

Upvotes: 1

Related Questions