Home  Typescript   Unable to i ...

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:

  1. Runtime Values: Use import { ... } from 'module'; for values that exist at runtime.

    import { Server, Socket, Namespace } from 'socket.io';
    
  2. 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:

Published on: Jun 25, 2024, 11:25 PM  
 

Comments

Add your comment