如何在定义为"any"的第三方TypeScript接口中扩充属性?

Nat*_*end 8 module interface typescript

给定第三方TypeScript模块,如下所示:

// in /node_modules/third-party-module/index.d.ts
declare module 'ThirdPartyModule' {
    export interface ThirdPartyInterface {
        data: any;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何扩充此模块以更严格地键入data属性?

我试过这个:

// in /app/typings.d.ts
declare module 'ThirdPartyModule' {

    interface IMyCustomType {}

    interface ThirdPartyInterface {

        // causes a compiler error: Subsequent property declarations 
        // must have the same type.  Property 'data' must be of type 
        // 'any', but here has type 'IMyCustomType'.
        data: IMyCustomType;
    }
}
Run Code Online (Sandbox Code Playgroud)

但这给了我一个编译器错误:"后续属性声明必须具有相同的类型.属性'数据'必须是'any'类型,但这里的类型为'IMyCustomType'."

如果第三方模块将属性定义为实际类型,如下所示:

// in /node_modules/third-party-module/index.d.ts
declare module 'ThirdPartyModule' {
    interface IAnotherThirdPartyInterface {
        something: string;
    }

    interface ThirdPartyInterface {
        data: IAnotherThirdPartyInterface;
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以简单地让我的IMyCustomType界面扩展这个第三方类型:

// in /app/typings.d.ts
declare module 'ThirdPartyModule' {
    interface IMyCustomType extends IAnotherThirdPartyInterface {}

    interface ThirdPartyInterface {
        data: IMyCustomType;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,由于定义了类型any,我无法扩展它:

// causes a compiler error:  'any' only refers to a type, 
// but is being used as a value here.
interface IMyCustomType extends any {}
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 8

虽然您无法重新定义该属性,但另一种方法是定义一个新属性,并使用此新属性扩充原始对象。虽然此解决方案并不普遍适用,但如果该属性在一个类上,则可以完成。在你的情况下,你在评论中提到hapi。由于该属性在Server类上,我们可以定义该属性的新类型版本。

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;
    }
});
Run Code Online (Sandbox Code Playgroud)

用法.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: '/',
    handler: function (request, reply) {
        reply(request.server.typedApp.myData);
    }
});
Run Code Online (Sandbox Code Playgroud)