unable to import exported members from the ts file
Understanding the distinction between importing types and runtime values is crucial in TypeScript. When you encounter named exports that don't exist at runtime, it’s often because they are type definitions rather than actual JavaScript values.
Summary of Correct Import Practices:
-
Runtime Values: Use
import { ... } from 'module';
for values that exist at runtime.import { Server, Socket, Namespace } from 'socket.io';
-
Type Definitions: Use
import type { ... } from 'module';
for types that are only used at compile time.import type { ServerOptions, BroadcastOperator, RemoteSocket } from 'socket.io';
Example Code:
Here’s a full example incorporating both runtime values and type definitions:
// Import runtime values
import { Server, Socket, Namespace } from 'socket.io';
// Import types only
import type { ServerOptions, BroadcastOperator, RemoteSocket } from 'socket.io';
// Server options example
const options: ServerOptions = {
// server options here
};
// Creating a new Server instance
const server: Server = new Server(options);
// Handling a new connection
server.on('connection', (socket: Socket) => {
console.log('A user connected');
});
// Example usage of a BroadcastOperator
const broadcaster: BroadcastOperator<RemoteSocket<unknown, unknown>> = server.local;
broadcaster.emit('message', 'Hello to all connected clients!');
Why This Matters:
- Type Safety: Using
import type
ensures you only bring in type definitions and avoid unnecessary code in your JavaScript bundle. - Clear Distinction: It helps distinguish between what is available at runtime and what is only used for type checking, making your code more maintainable.
Published on: Jun 25, 2024, 11:25 PM