【问题标题】:Is there a way to extend a third party library type with same name in TypeScript有没有办法在 TypeScript 中扩展同名的第三方库类型
【发布时间】:2021-03-17 12:34:53
【问题描述】:

Luxon 日期库具有 DateTime 类型。而不是直接从luxon 库中导入 DateTime,比如import { DateTime } from 'luxon';,我想扩展库以使用可以在项目组件中使用的自定义类型,这将使​​我们能够替换第三方库将来在一个地方在需要时与另一个地方。

第一个问题:是否有任何简单的方法可以在不自定义扩展库的情况下做到这一点? 如果没有,那么是否可以使用相同的名称? (AFAIK 没有)

export interface {CustomPrefixName}DateTime extends DateTime {

}

这可行,但有什么办法可以去掉前缀名称?

然后在组件中导入自定义日期时间

import { CustomDateTime } from 'somewhereInProject';

【问题讨论】:

  • 您应该能够在项目的任何目录中简单地创建一个新文件、名为 DateTime 的类或接口。将 luxon 库导入该文件,然后将新创建的具有 DateTime 名称的文件导入您想要的任何位置,但使用新的导入。导入名称取决于文件所在的位置,因为 TypeScript 中并没有真正使用命名空间。然后,如果您更改了基础库,您只需更改自定义 DateTime 类文件中的导入位置,前提是存在相同的方法和属性。
  • 你说export interface DateTime extends DateTime { }是允许的?
  • 哦,是的,我认为你是对的,会有名称冲突。这个链接有帮助吗? Import two classes with the same name 所以它会是: import {CustomDateTime as DateTime} from '../myCustomDateTimeClass'

标签: javascript angular


【解决方案1】:

这行得通

import {DateTime as LuxonDateTime} from 'luxon'

export interface DateTime extends LuxonDateTime {
    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多