TypeScript:访问本地 class 定义隐藏的全局类型?

TypeScript: Access global type hidden by local class definition?

假设我有一个 class,它与先前定义的类型同名,该类型在 lib.d.ts 中定义。我将如何在此 class.

中使用该类型

例如,我有 class Event,它必须处理浏览器 Event 对象,它是定义为 lib.d.ts.

中的接口
export class Event { // own definition of Event which hides original Event

  public dealWithBrowserEvent(event: Event): void { // Event object defined by lib.d.ts
    // deal with it
  }

}

我如何告诉 Typescript 这是两种不同的类型。当然,我可以简单地重命名我的 class,但我不想那样做,因为这个名字非常适合我的用例。

您可以这样做存档:

E.ts:

class CustomEvent 
{ 
    public dealWithBrowserEvent(event: Event): void 
    { 

    }
}

export default CustomEvent;

A.ts:

import Event from './E'

export class SomeClass 
{ 
    //Parameter e here is instance of your CustomEvent class
    public someMethod(e: Event): void 
    { 
        let be: any;
        //get browser event here
        e.dealWithBrowserEvent(be)
    }
}

更多关于声明合并,以及什么可以合并,什么不能:link

强烈建议您不要这样做。这段代码会给你的同事带来很多困惑 reading/modifying ,更不用说不能在同一文件标准中使用 Event.class 的头痛了。

与此同时,我找到了一个非常可行的解决方案。我定义了一个附加模块来导出重命名的接口。如果我导入这个模块,我可以使用重命名的类型,就好像它们是原始类型一样。

browser.ts

// Event will be the one from lib.d.ts, because the compiler does not know anything about 
// the class Event inside this module/file.
// All defined properties will be inherited for code completion.
export interface BrowserEvent extends Event {
    additionalProperty1: SomeType;
    additionalProperty2: SomeType;
}

如果您不需要额外的属性,您可以只做类型别名:

browser.ts

// Alias for Event
export type BrowserEvent = Event;

event.ts

import {BrowserEvent} from './browser.ts';

export class Event { // Definition of Event hides original Event, but not BrowserEvent

  public dealWithBrowserEvent(event: BrowserEvent): void {
    // deal with it
  }

}

我对这个解决方案很满意,但也许还有更好的解决方案。