2

In a React web app I have a typescript module from which I'm exporting a series of types, and I want to import some of them into my App.tsx. The module exporting the types looks like this:

// poker_messages.ts
export type Card = { suit: string; rank: string };
//...
export type IncomingPokerMessage = General | PlaceBet | Error;

In App.tsx I can import them like this:

import * as PM from './poker_messages';

Then refer to the types as PM.Card etc. But if I try

import { Card, IncomingPokerMessage } from './poker_messages';

I get an error that the module does not export those names. What's the right way to import only those things I need and without the qualified name?

1
  • import type { Card, IncomingPokerMessage } from './poker_messages'; or try { "compilerOptions": { "isolatedModules": false } } Commented Nov 10 at 11:55

1 Answer 1

3

instead of

import { Card, IncomingPokerMessage } from './poker_messages';

do

import type { Card, IncomingPokerMessage } from './poker_messages';

notice the added type after the import. since the types do not exist at runtime, typescript requires types and interfaces to be explicitly imported as so:
import type { A } from './foo';
or
import { type A } from './foo';

the first one is preferred here since there is more than 1 type import.

however if you would like to just do import { A } from './foo'; you could enable verbatimModuleSyntax in your tsconfig.json. (i do not recommend doing this since it is implicit).

why `

import * as PM from './poker_messages';

worked was because this is a namespaced import, it states that 'i would like to import from poker_messages.ts as namespace named PM.' and yes, that includes exported types from the module too.

here is the documentation for typescript modules:
https://www.typescriptlang.org/docs/handbook/modules/reference.html

here are the documentation for verbatimModuleSyntax:
https://www.typescriptlang.org/tsconfig/#verbatimModuleSyntax

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.