【问题标题】:How to export a collection of Interfaces in typescript如何在打字稿中导出接口集合
【发布时间】:2017-12-25 15:59:03
【问题描述】:

我有一个文件actions.ts,它声明了一堆动作类型。

actions.ts

export interface Action1 extends Action {
type: types.Action1Type
}

export interface Action2 extends Action {
type: types.Action2Type
}

export interface Action3 extends Action {
type: types.Action3Type
}

我在 index.ts 中导入这些操作:

import * as actions from './actions';

index.ts 文件中actions变量的类型是什么?我希望能够在 actions.ts 文件本身中创建此构造并将其导出。类似于以下内容:

actions.ts

interface Action1 extends Action {
type: types.Action1Type
}

interface Action2 extends Action {
type: types.Action2Type
}

interface Action3 extends Action {
type: types.Action3Type
}

export const Actions = {
  Action1,
  Action2,
  Action3,
}

但这给了我一个错误:

Action1 仅指一种类型,但在这里用作值。

【问题讨论】:

    标签: typescript interface


    【解决方案1】:

    接口只是 TypeScript 中的类型定义,因此您不能使用操作创建变量(将它们用作值)。

    您可以使用命名空间来组合您的操作:

    namespace Actions {
    
      export interface Action1 extends Action {
        type: types.Action1Type
      }
    
      export interface Action2 extends Action {
        type: types.Action2Type
      }
    
      export interface Action3 extends Action {
        type: types.Action3Type
      }
    
    }
    

    这允许您执行以下操作:

    import {Actions} from './actions';`
    

    但这与import * as actions from './actions';基本相同。您不能使用 Actions 作为值。

    【讨论】:

    • 我实际上也倾向于在 actions.ts 文件中包含所有动作类型的联合。 FeatureActions = Action1|Action2|Action3;但是 import * 包括了它,我只是想要它,就像你展示的那样。所以在我的 tslint 规则中允许 namespace 。实际上看起来并不坏。从'../../actions'导入{动作,FeatureAction};谢谢。
    猜你喜欢
    • 2019-11-12
    • 2017-09-02
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多