【问题标题】:How to export type in typescript, it marks the type as undefined如何在打字稿中导出类型,它将类型标记为未定义
【发布时间】:2020-06-08 01:27:42
【问题描述】:

我需要将我的types 放在一个单独的文件中,在其中创建它并将其导出为默认值,如下所示:

type props = {
    playerId: string;
    isAutoplayPrevented: boolean;
}

// 'props' is not defined.eslint(no-undef)
export default props;

虽然我已经定义了props,但我收到了一个 ESLint 警告,指出propsundefined。 我是否应该忽略该警告并停止 ESLint 投诉,如下所示:// eslint-disable-next-line no-undef

或者还有其他更合适的解决方案吗?

【问题讨论】:

  • 还要检查您的 linter 版本,因为这个 TS 功能(仅类型导入和导出语法)是相当新的(TS >= 3.8)。我在最新版本 "typescript": "^3.8.2""eslint": "^6.8.0""@typescript-eslint/eslint-plugin": "^2.20.1-alpha.5" 中没有收到该警告,尽管在使用该类型设置变量时出现了另一个关于 "error 'props' is defined but never used no-unused-vars" 的错误。

标签: javascript reactjs typescript types


【解决方案1】:

我建议您考虑为类型和写入类型分开的文件,如下所示:

export type General = {
  classes: Record<string, string>,
};

export type AxiosCall = {
  // etc
};

// etc

您可以在其他组件上轻松import 使用它。

【讨论】:

  • 感谢您的回答,这是一个命名导出。我如何进行默认导出或您根本不建议默认导出?
  • 亲爱的@TheoItzaris,默认导出防止破坏导入,除了创建组件等某些情况外,我不熟悉它。我的一位朋友告诉我,这种情况下的默认导出会导致捆绑文件出现代码重复,但我不确定。
  • @TheoItzaris,最好有一个命名导出,因为这样可以让您的代码在导入时保持一致。 Bcoz,使用默认导出,任何导入此类型的组件都会按照他们的意愿命名它,我没有,假设有办法导出默认类型。
猜你喜欢
  • 2020-03-18
  • 1970-01-01
  • 2017-04-13
  • 2017-04-19
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
相关资源
最近更新 更多