打字稿声明合并库类型

问题描述 投票:2回答:2

有人知道如何“扩展”(通过声明合并)接口的声明,在那里从typescript的库文件中声明?

在我的情况下,我想扩展库lib.dom中typescript构建的接口HTMLCanvasElement。我知道声明合并是如何工作的,但我没有得到HTMLCanvasElement接口的正确导入。

import {HTMLCanvasElement} from '<what.to.use.here>';

declare module '<what.to.use.here>'{
    interface HTMLCanvasElement{
        //add my stuff
    }
}

谢谢 :)

typescript type-declaration
2个回答
2
投票

这些类型存在于全局命名空间中。如果您在脚本文件(即不是模块)中,则可以重新声明它。如果您在模块中,则需要在global中声明它,无需导入。

declare global{
    interface HTMLCanvasElement{
        my:number
    }
}

export var x = 1;// just to make this module
let c: HTMLCanvasElement;
c.animate // regular stuff 
c.my //my stuff 

0
投票

声明合并意味着编译器将使用相同名称声明的两个单独声明合并到一个定义中。

请参阅以下示例,其中接口声明在typescript中合并

    interface Boy {
    height: number;
    weight: number;
    }

    interface Boy {
    mark: number;
    }

    let boy: Boy = {height: 6 , weight: 50, mark: 50}; 

declaration merging

© www.soinside.com 2019 - 2024. All rights reserved.