【问题标题】:How to re-export types as global in TypeScript如何在 TypeScript 中将类型重新导出为全局类型
【发布时间】:2020-09-10 09:45:14
【问题描述】:

我想要一个可以全局访问的接口(在单独的文件中定义),我该怎么做?

这是我的globals.d.ts 文件

import { Theme, Style } from './style/themes/theme.types'

declare global {
  Theme
  Style
}

这给了我一个错误

Statements are not allowed in ambient contexts.ts(1036)
'Theme' only refers to a type, but is being used as a value here.ts(2693)

【问题讨论】:

  • 有一些 hacky 解决方案,例如在别名下导入,然后声明全局类型别名 import { Theme as TM } from './style/themes/theme.types'; declare global { type Theme = TM; },但这很尴尬,与您所描述的不完全一样。你为什么做这个?用例是什么?这似乎很可疑。
  • 很怀疑,我认为在类型定义文件中定义类型比尝试导入它们更好
  • 你很困惑。该文件是.d.ts 还是.ts 与您是否导入它们无关。如果我能理解它,我会回答你的问题。
  • 是的,我认为我的问题没有意义,我会在有时间的时候发布解决问题的方法。

标签: typescript interface export


【解决方案1】:

这可能是一个 hack,因为如果放在 .ts 文件中会引发错误,但放在 .d.ts 文件中时似乎可以工作。

这个想法是用一个名称导入类型并用另一个名称导出。

src/globals.d.ts:

import type { DeepPick as _DeepPick } from "ts-deep-pick";
declare global {
  export { _DeepPick as DeepPick };
}

【讨论】:

  • 添加到这里,你可以export interface Theme extends _Theme。当您想要扩展 Emotion emotion.sh/docs/emotion-11#theme-type 等库的接口时很有用
  • 对我来说,即使在 .d.ts 文件中仍然存在错误。只需在其前面添加 // @ts-ignore: export typing 行。
猜你喜欢
  • 2015-07-25
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 2020-06-27
  • 1970-01-01
  • 2017-11-28
  • 1970-01-01
  • 2020-05-15
相关资源
最近更新 更多