Reputation: 607
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: {}});
Upvotes: 0
Views: 428
Reputation: 29179
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.
Upvotes: 1
Reputation: 99816
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.
Upvotes: 0