相关疑难解决方法(0)

如何在定义为"any"的第三方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 …
Run Code Online (Sandbox Code Playgroud)

module interface typescript

8
推荐指数
1
解决办法
1773
查看次数

如何在Typescript中覆盖或扩展库类型定义

如果我在Typescript中导入库类型声明。当存在编译器问题时,如何扩展该库的定义,但是如果不是这样,它将是有效的js代码?例如,validate.js类型绑定与实际实现相比非常不准确。如下图所示。

import * as validate from 'validate.js';

declare namespace validate {
  Promise: any;
  async: any;
}
Run Code Online (Sandbox Code Playgroud)

与猫鼬类似,我无法访问modelSchemas属性,但需要。

import * as mongoose from 'mongoose';
declare namespace mongoose {
  export modelSchemas any[];
}
Run Code Online (Sandbox Code Playgroud)

因此,如果我想向现有类型添加定义只是为了关闭编译器。我怎样才能做到这一点?

typescript

5
推荐指数
1
解决办法
5866
查看次数

标签 统计

typescript ×2

interface ×1

module ×1