3

Is is it possible to override a function signature of a external package with your own types?

Let's say I have a external package called translationpackage and I want to use the translate function of it.

The package defines the function as follows:

// original signature
function translate(key: string) : string;

Now I want to override it to only accept the keys 'foo' | 'bar'. Which would be written like the following example if I would implement the translate function my self.

// my own signature
function translate(key: 'foo' | 'bar'): string

What do I have to do in order to get Typescript to use my own signature instead of the original one everywhere I import translate?

import { translate } from 'translationpackage'

Edit: I know that d.ts files can be used if the imported module has no own type definitions. However it seems that this does not work when I try to override existing types.

The following code is almost what I'm looking for but typescript ignores it in favor of the types that come with the package.

declare module 'translationpackage' {
  export function translate(key: 'foo' | 'bar'): string;
}
icalvin102
  • 117
  • 8
  • But that's exactly how you do it.. `function translate(key: 'foo' | 'bar'): string` is the solution. What's the problem you're having? – Mohamed Karkotly Sep 12 '21 at 19:10

1 Answers1

0

You will have do implement a translate wrapper for yourself that wraps the function from translatepackage.

// my-translate.ts
import { translate } from 'translationpackage'

export const myTranslate = (key: 'foo' | 'bar'): string => translate(key)

// my-other-file.ts
import { myTranslate } from 'my-translate'

console.log(myTranslate('foo'))
ryok90
  • 92
  • 2