Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript errors when importing a "not exported" type, even though it is exported

I'm using Typescript, React & Redux (if relevant). My project structure:

/project
  /src
    /actions
      index.ts
      actions.ts

index.ts

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

export { Action }

I re-export Actions in index.ts so that other files (not under the /actions directory) can import the Actions type using import { Action } from "./actions"

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)

I get this error:

Type error: Module '"<snipped path>"' has no exported member 'Action'.
TS2305

When I try to import Action anywhere.

Any ideas?

like image 299
haz Avatar asked Jan 02 '23 05:01

haz


1 Answers

Typescript 3.8 introduces new syntax for type-only imports and exports:

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';

This enables exporting types via index.ts (module's public API) files as we would do with other exported members. Just add type keyword in front of destructured types/interfaces:

export type { Actions } from './actions';

 


In the earlier versions of Typescript (before 3.8) to make it work, it's necessary to reexport imported types:
(looks pretty ugly, but does the job)

import { Actions as _Actions } from "./actions";
export type Actions = Actions;

References:
- https://devblogs.microsoft.com/typescript/announcing-typescript-3-8-beta
- https://github.com/microsoft/TypeScript/pull/35200

like image 169
Nik Sumeiko Avatar answered Jan 05 '23 18:01

Nik Sumeiko