Enforcement of Typescript Field Type Lax During Assignment

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.

Answer №1

TypeScript does not perform checks at runtime. By defining the type of data as shown below:

userData: { 
  username: string,
  age: number
}

TypeScript verifies that the userData.age type aligns with the expected type for the constructor's age parameter during compilation, which it successfully accomplishes. However, if there is doubt about whether the incoming data matches the declared type, a runtime check is essential.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize Django to leverage a JSON file stored within a context variable for use in jQuery

I need to utilize a list in Jquery and integrate it with the Autocomplete jQueryUI widget. The list is small, so creating a new request seems unnecessary. Therefore, I believe using Jsquery's getJSON is also not required. Here is my current setup: ...

Enhance the appearance and format of white space in JavaScript code

I'm in search of a solution to automatically beautify whitespace in my JavaScript code. I have come across tools like JSLint and JSHint that can check for indentation and trailing spaces, but they might not cover all types of whitespace issues. My ch ...

Steps to Incorporate jQuery Function in a Partial View Inside a Modal

My jquery button click method is functioning correctly in views outside of modals, but the uploadbtn button click method does not work when a partial view is loaded in the modals. <script src="~/lib/jquery/dist/jquery.min.js"></script> ...

Creating a function that takes a second parameter inferred from a mapped type, depending on the first parameter given

Here is a snippet of code similar to the example provided: export enum Group { FOO = 'foo', BAR = 'bar', BIZ = 'biz' } interface Mapping extends Record<Group, any> { [Group.FOO]: {fooString: string; fooN ...

Error encountered while attempting to obtain OAuth2 API authorization token in ExpressJS Node.js Angular: "getaddrinfo ENOTFOUND"

Recently, I developed an angular application that sends an HTTP post request to a Node/Express.js endpoint upon clicking a button in order to obtain an authorisation token. I successfully configured the necessary credentials for basic OAuth2 authorisation ...

enabling input field while making asynchronous requests with jQuery

This is the code snippet from my index.php file: <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="ajax.js"></script> <script> $("input" ...

Ensure the text value of a collection of web elements by utilizing nightwatch.js

Recently, I started using nightwatch.js and I am trying to retrieve a list of elements to verify the text value of each element against a specific string. Here's what I have attempted: function iterateElements(elems) { elems.value.forEach(funct ...

When a Vue.js Directive is inserted or bound, it actually takes precedence over the click event

Imagine having multiple dropdowns or elements on the page that all utilize a directive called "closable". This directive triggers an expression if the element clicked is outside of the element using the directive. The intended behavior is that when clicki ...

Contrasting outcomes between calling the await method in a function and directly logging the same method

My code consists of a for loop that iterates through an array. With each iteration, I intend for the loop to extract the value from a specified webpage and then display it in the console. for (let i = 0; i < jsonObjSplit.length; i++) { console ...

Managing User Feedback with Ajax, JQuery, and PHP

Imagine you're using ajax to send data. The server processes it (in PHP) and sends back a response that can be captured with complete: function(data) { //WRITE HTML TO DIV $('#somehing').html(data) } The big question is: how can you modify ...

Vue 4 and TypeScript: Dealing with the error message 'No overload matches this call'

In my Vue-Router 4 setup, I am trying to combine multiple file.ts files with the main vue-router (index.ts) using TypeScript. However, it throws an error that says "TS2769: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray[]): ne ...

Fill a dropdown menu with options from a JSON object, arranging them in ascending order

I have a JSON hash that I am using to populate a combo box with the following code: $.each(json_hash, function(key, value) { $("#select").append("<option value='" + key + "'>" + value + "</option>"); }); The functionality w ...

Issue with AngularJS: $compile function is not functioning as expected

In this particular code snippet, I am encountering an issue with the $compile function. What I am trying to accomplish is taking an item, adding it to the scope, and then compiling it to generate HTML. $http({ method: 'GET', ...

Prevent using keys of nullable properties as method parameters in Typescript generics

What is the solution to disallow a method from accepting a parameter of type keyof this where the property is nullable? Consider the following example: abstract class MyAbstractClass { get<K extends keyof this>(key: K): this[K] { return this[k ...

The resizing of the window does not trigger any changes in the jQuery functions

Here is a snippet of jQuery code that executes one function when the window size is large (>=1024) and another when it is resized to be small. Although the console.logs behave as expected on resize, the functions themselves do not change. This means th ...

Upon loading the React Login page, the focus immediately shifts to the 'password' field rather than the 'username' field

I am currently in the process of building a login page using React. The code below is from my input.jsx file where I have imported Bootstrap components. import React from "react"; const Input = ({ name, label, value, onChange, error }) => { ...

Using Slick Slider and Bootstrap CSS to display text on top of images

Currently, I am utilizing the slick slider from and I want to overlay text on top of the image. I tried using bootstrap carousel-caption, which works well with any image. However, with slick slider, it seems like the text is not at the highest level as I ...

Limiting JSDoc/TypeScript type to a specific array element

Utilizing TypeScript with JSDoc poses a challenge as I aim to restrict a variable to one of the known values stored in an array. I am aware that it can be achieved like so: /** @type {'one'|'two'|'three'} */ let v = 'fo ...

Leveraging the Map function with Arrays in TypeScript

Is there a way to dynamically render JSON data into a component using array.map in Typescript? I am running into an error with the code snippet below. const PricingSection: FC<IProps> = ({ icon, title, price, user, observations, projects, intervie ...

Changing the text of a link when hovering - with a transition

Seeking a straightforward way to change text on a link upon :Hover. I desire a gentle transition (text emerges from below) and fallback to default if JavaScript is disabled. HTML <div class="bot-text"> <a href="">Visit this site</a> ...