Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override type provided by TypeScript library in a namespace?

Tags:

typescript

Is there any way to override the value of a type exported and used by a TypeScript package?

So I have this in my typings file:

// index.d.ts
declare module 'my-package' {
    namespace DependencyInjection {
        type ServiceID = 'myServiceOne' | 'myServiceTwo'; // original type is "any";
    }
}

and I get the following the error:

Duplicate identifier 'ServiceID'.ts(2300)
inject.ts(44, 10): 'ServiceID' was also declared here.

I'd like to be able to replace the type of ServiceID from the consuming code. Can it be done? I know interfaces can be extended but I haven't found a way to change or update a type.

Context

I'm writing a TypeScript package and I'd like users to be able to override some default types with their own when they integrate the package, rather than having to provide generics every time they use some methods.

like image 821
James Cook Avatar asked Aug 31 '20 20:08

James Cook


1 Answers

Module augmentation only work if the module can be extended. Types cannot be extended, but interfaces can.

declare module 'my-package' {
    namespace DependencyInjection {
        interface ServiceIDMap {}
        type ServiceID = keyof ServiceIDMap
    }
}

declare module 'my-package' {
    namespace DependencyInjection {
        // insert your keys in here.
        interface ServiceIDMap {
            myServiceOne: unknown
            mySevriceTwo: unknown
        }
    }
}

Playground

@types/jest is designed to do this too, with ts-jest extending the Config.InitialOptions.globals struct.

like image 119
Wayne Van Son Avatar answered Oct 12 '22 19:10

Wayne Van Son