How can I augment a property within a third-party TypeScript interface defined as “any”?

While you can’t redefine the property, an alternative would be to define a new property, and augment the original object with this new property. While this solution is not generally applicable, if the property is on a class it can be done. In your case you mention in the comments hapi. Since the property is on the Server class we can define a new typed version of the property.

hapi.augment.ts

import *  as Hapi from 'hapi'

declare module 'hapi' {
    export function server(cfg: any): Hapi.Server;
    interface Server {
        typedApp:  {
            myData: string
        }
    }
}

Object.defineProperty(Hapi.Server.prototype, 'typedApp', {
    enumerable: false,
    get(this: Hapi.Server){
        return this.app;
    },
    set(this: Hapi.Server, value: any){
        this.app = value;
    }
});

usage.ts

import *  as Hapi from 'hapi'
import './hapi.augment'

const server = new Hapi.Server()
server.connection({ port: 3000, host: 'localhost' });
server.start();
server.typedApp.myData = "Here";

server.route({
    method: 'GET',
    path: "https://stackoverflow.com/",
    handler: function (request, reply) {
        reply(request.server.typedApp.myData);
    }
});

Leave a Comment