My current issue involves a constructor that is supposed to set the value of _device. The field is specifically designed to be of type number, and the constructor parameter is also expected to be of type number. However, when a parameter of type string is passed to the constructor, it incorrectly assigns that string to the field which should only accept numbers.
I have attempted checking the type of the incoming argument strictly to ensure it is a number, but I would prefer Typescript to handle this validation automatically for me.
I suspect that the problem may lie in how the socketio arguments are being received. I'm considering if it is acceptable to declare a type like this within the code:
{
joinRoom: {
roomId: string,
intent: number
},
playerData: {
name: string,
device: number
}
}
Player Class
export class Player {
private _name: string;
private _socketId: string;
private _isReady: boolean;
private team: string;
private _device: number;
/**
* Creates an instance of Player.
* @param {string} name
* @param {string} socketId
* @param {number} device
* @memberof Player
*/
constructor(name: string, socketId: string, device: number) {
this._name = name;
this._isReady = false;
this._socketId = socketId;
this._device = device;
}
...
RoomLogic Class
/**
* @private
* @param {*} socket
* @memberof RoomLogic
*/
private joinRoom(socket: any) {
socket.on(CONSTANTS.JOIN_ROOM,
(
joinRoom: {
roomId: string,
intent: number
},
playerData: {
name: string,
device: number
}
) => {
const noRooms = this.utils.isObjectEmpty(this._rooms);
const roomAlreadyExists = !this.utils.isUndefined(this._rooms[joinRoom.roomId]);
const isValid = this.isPlayerDataValid(playerData);
if (isValid.isSuccessful === false) {
return socket.emit(CONSTANTS.JOIN_ROOM, isValid);
}
if (this.utils.isSame(joinRoom.intent, JoinRoomIntents.CreateNewRoom)) {
// should never be hit, but keep in case
if (roomAlreadyExists) {
return socket.emit(CONSTANTS.JOIN_ROOM, {
isSuccessful: false,
value: `room with id: ${joinRoom.roomId} already exists`
});
}
let player = new Player(playerData.name, socket.id, playerData.device);
...
In conclusion, my expectation is for Typescript to detect these issues and either throw an error during compilation or at runtime.