Tuesday, 17 May 2022

Typescript: Changing the definition of some third party types d.ts

I am a little bit lost how to do the following.

I am trying to change the definitions of some third party types by creating a new file thirdParty.d.ts.

Let's suppose the third party returns Class A

class A {
    // ...
}

In my third-party.d.ts file, I want to introduce two new parameters.

import * as thirdParty from 'thirdParty'
decalre module 'thirdParty' {
    export interface A extends thirdParty.A {
        newParam1: number
        newParam2: number
    }
}

Then, let's overwrite class A by adding newParam1 and newParam2

class ExtendedA extends A {
    newParam1 = 1
    newParam2 = 2
}

So now everything looks good. Every instance of class A recognizes the new parameters. In any function or class it's possible to call newParam1 without casting.

randomMethod() {
 console.log(this.a.newParam1) // Returns 1. No need to cast (this.a as ExtendedA).newParam1 !
}

However, since I changed the definition of class A. And ExtendedA extends it. Deleting the new parameters will not generate errors. Which worries me. I am looking for a way to force ExtendedA to decalre the new parameters.

// This is bad :(    
class ExtendedA extends A { // implements Interface will not work either
    // newParam1 = 1 // Commented but there is no errors ! Which is bad
    // newParam2 = 2
}

I am sure the fix is pretty easy but I am really lost



from Typescript: Changing the definition of some third party types d.ts

No comments:

Post a Comment