0

I'm new to Typescript. I'm stuck at the interfaces part. Using Nodejs I send an object from the client to the server called startData. This object contains an ID and Username. I'm using an interface to define the types in this object. I define testId as a number and Username as a string.

However, when I send for example testId as a string and Username as an object, no error gets thrown. Why does the interface accept the wrong types? I would expect it to throw some kind of unexpected type error.

interface startDataInterface{
    testId: number;
    username: string;
}

socket.on('startData', function(startData: startDataInterface) {
   ...

I'm sending this on the client:

socket.emit('startData', {testId: "string", username: {}});

2 Answers 2

1

The socket method on only accepts generic functions, so typescript will not report an error on the receiving side. Extend or delegate socket and write a typesafe wrapper if you need that degree of type checking.

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

Comments

0

You are probably extending EventEmitter, which, by default has any for it's emit arguments.

Anytime any is used, typechecking effectively is disabled. By default there's also no relationship between what was emitted and what was caught with on.

It's possible to create very specific on and emit method, via overloading. For instance, you can define your emit method as such:

emit: function(eventName: 'startData', startData: StartDataInterface);
emit: function(eventName: string...args: any) {
}

With a signature like this, typescript will know how to enforce these types for the startData event, but you will also have to add the same type of overloaded signature on the on method.

2 Comments

I'm sorry, I don't understand. Why are you using two emit functions here to catch one message?
@P.Yntema they are not 2 functions. It's one function with multiple overloaded definitions. Take a look at the official documentation (search for overloads on this page) typescriptlang.org/docs/handbook/functions.html

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.