【问题标题】:Typescript exporting and reexporting interface and other dataTypescript 导出和再导出接口等数据
【发布时间】:2016-12-26 07:29:34
【问题描述】:

我是打字稿的新手。如何从特定文件中导出类型定义(类、接口)+所有变量?我试过这个:

models.ts

export interface CounterState {
    count: number;
}

let t = 5;
export {t}; 

index.ts

import * as models from './models';
models.t -> ok
models.CounterState -> not visible, why?
export default  { models };

reducer.ts

import CounterStore from "./index";


CounterStore.models.t -> ok
CounterStore.models.CounterState -> not visible, why?

为什么 * 没有导入所有内容? 如果我这样做:import {CounterState} from "./models";它会起作用。

编辑:如果我将接口更改为类,它会按预期工作。

【问题讨论】:

    标签: typescript import export


    【解决方案1】:

    问题不在于导入/导出,而在于您尝试评估接口,这是不可能的:

    • 实际的接口声明没有编译成任何javascript,所以在编译的js中尝试调用models.CounterState没有任何意义。

    • 然而,如果你声明一个类,你确实有一个编译结果。这就解释了为什么这不会引发错误。

    我只想再次大声疾呼打字稿错误的极端晦涩之处。 ?

    对于两者的区别,看看equivalent playground example 和它编译成什么:

    interface ICounter { // No compilation result
      count: number 
    }
    
    class Counter { // has actual compilation result
      count: number
    }
    
    let interfaceImplemenetation: ICounter // Compiles fine
    Counter // Compiles fine
    ICounter // Compiles to undefined
    

    【讨论】:

    • 感谢您的澄清,jaysoo.ca/2016/02/28/organizing-redux-application -> 如何在打字稿中遵循这些规则?我的意思是创建包含其他模块所有内容的索引?
    • 我不是 100% 确定你的意思。如果我正在创建 redux 应用程序,我通常只是将我的状态接口放在根的某个全局声明文件中(例如 index.d.ts),然后我不必到处导入它¯\_(ツ) _/¯。 (如果这是你的问题?)
    • 是的,但每个减速器都有一个状态。我说的不是全局状态,而是单个 reducer 状态,稍后当我将它们组合成全局状态时,我需要引用它
    • 我认为目前还没有最佳实践。我认为在 reducer 文件中声明 reducer 状态的接口,并在声明全局状态时导入所有这些是非常直观的。
    猜你喜欢
    • 2015-08-23
    • 2019-07-14
    • 1970-01-01
    • 2017-05-31
    • 2020-03-06
    • 2018-08-24
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    相关资源
    最近更新 更多