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?
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