How to correctly override / augment a type from an npm library using TypeScript module augmentation?

4 weeks ago 14
ARTICLE AD BOX

I’m trying to override a type that comes from my library that was published on npm.

The library exposes a structural directive that uses a Permission type to ensure correct typing in templates:

<div *permissions="'ALLOW_X'">bla</div>

The library’s directive relies on a Permission type declared in its .d.ts.


What I want

I want the application (not the library) to define the valid permission values, using TypeScript module augmentation, so that:

<div *permissions="'bla'">bla</div>

produces a TypeScript error, while valid values like 'ALLOW_X' are allowed.


My attempt (application-level .d.ts)

import 'my-jon-permissions'; declare module 'my-jon-permissions' { export type Permission = 'ALLOW_X' | 'ALLOW_Y'; }

Problems I’m seeing

In StackBlitz
I get a TypeScript error:

Duplicate identifier 'Permission'

In cursor IDE (same code)
There is no error, but the directive input is inferred as:

declare (property) PermissionsDirective.permissions: string

Meaning the type augmentation doesn’t seem to apply at all.
enter image description here


Usage example

import { Component } from '@angular/core'; import { bootstrapApplication } from '@angular/platform-browser'; import { PermissionsDirective } from 'my-jon-permissions'; @Component({ selector: 'app-root', imports: [PermissionsDirective], template: ` <div *permissions="'bla'">bla</div> `, }) export class App {} bootstrapApplication(App);

Question

What is the correct way to override / augment a type from an npm library so that:

The directive input is strongly typed

The type is defined at the application level

No Duplicate identifier errors occur

Angular template type checking respects the augmented type.

stackblitz demo

Read Entire Article