导入“未导出”类型时出现打字稿错误,即使它已导出

haz*_*haz 3 import module export typescript redux

我正在使用 Typescript、React 和 Redux(如果相关)。我的项目结构:

/project
  /src
    /actions
      index.ts
      actions.ts
Run Code Online (Sandbox Code Playgroud)

索引.ts

import {
    Action,
} from "./actions";

export { Action }
Run Code Online (Sandbox Code Playgroud)

我重新导出Actionsindex.ts以便其他文件(不在/actions目录下)可以Actions使用import { Action } from "./actions"

动作.ts

// These are the general structures create each
// async action
type Request<T>  = { request: T }
type Response<T> = { response: T }
type Err         = { error: string }

// Alias common types for requests & responses
type EmptyRequest = Request<null>
type ValueRequest = Request<{ value: number }>

export type Action
    // UI Actions
    = ({ type: "INCREMENT_COUNTER", delta: number })
    | ({ type: "RESET_COUNTER" })
    // Aync Actions
    | ({ type: "SAVE_COUNT_REQUEST" } & ValueRequest)
    | ({ type: "SAVE_COUNT_SUCCESS" } & Response<{}>)
    | ({ type: "SAVE_COUNT_FAILURE" } & Err)
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

Type error: Module '"<snipped path>"' has no exported member 'Action'.
TS2305
Run Code Online (Sandbox Code Playgroud)

当我尝试在Action 任何地方导入时。

有任何想法吗?

Nik*_*iko 8

Typescript 3.8 引入了仅类型导入和导出的新语法

import type T from './module';
import type { A, B } from './module';
import type * as Types from './module';

export type { T };
export type { T } from './module';
Run Code Online (Sandbox Code Playgroud)

这允许通过(模块的公共 API)文件导出类型index.ts,就像我们对其他导出成员所做的那样。只需type在解构类型/接口前面添加关键字

export type { Actions } from './actions';
Run Code Online (Sandbox Code Playgroud)

 


在早期版本的 Typescript(3.8 之前)中,要使其工作,需要重新导出导入的类型:(
看起来很丑,但确实有效)

import { Actions as _Actions } from "./actions";
export type Actions = Actions;
Run Code Online (Sandbox Code Playgroud)

参考文献:
- https://devblogs.microsoft.com/typescript/announcing-typescript-3-8-beta
- https://github.com/microsoft/TypeScript/pull/35200


Nin*_*liu 0

确保在导入操作时使用命名导入而不是默认导入:

// index.ts
import { Actions } from './actions';
export { Actions }
// elsewhere
import { Actions } from './path/to/src/action';
Run Code Online (Sandbox Code Playgroud)

或者,在索引和其他地方使用默认导出:

// index.ts
import { Actions } from './actions';
export default Action;
// elsewhere
import Actions from './path/to/src/action';
Run Code Online (Sandbox Code Playgroud)