A sophisticated method for converting a string to a number within a Typescript class without the need for a constructor?

Imagine needing to process JSON responses where all parameters are encoded as strings, regardless of their actual type. The goal is to strictly typecast these values into various Typescript classes. For example, consider the following JSON:

{"id":"1","label":"Alice"}

Now, let's say we have a Typescript class defined as follows:

class Person {
    public id:number;
    public label:string;
}

In other programming languages like AS3, it is possible to directly assign values without explicit type conversions, as shown below:

var p:Person = new Person();
p.id=jsonInput.id;
p.label=jsonInput.label;

However, in my particular case, I frequently encounter complex JSON objects that require dynamic creation, updates, and destruction of Typescript objects based on server data. It can be cumbersome to manually check if each parameter is numeric before assigning values. Even though a class property is declared as a specific type, such as number, at runtime it may still accept a string assignment without any validation.

This issue becomes especially troublesome when dealing with boolean values represented as "0" or "1" strings from the server. Forced comparisons with these strings are necessary, leading to inefficiencies.

Therefore, I am seeking an elegant solution to enforce type constraints specified in the class definition during property assignments. Rather than constantly checking for data types received from the server, I aim to utilize the class definition to automatically cast values appropriately. For instance, receiving a non-numeric string should result in either null or an error if assigned to a number property; assigning a number to a string property should yield a string value instead of throwing an error. Similar behavior is expected for boolean properties. Is there a way to achieve this level of type safety in Typescript as seen in other languages?

Answer №1

One approach is to utilize getter and setter functions.

By implementing getter/setter functions, you can add extra logic to ensure the variable is of the desired type.

class Person {
  private _id: string

  get id() {
    return this._id;
  }

  set id(val) {
    // Perform validation to convert the id into a string
    this._id = // properValue
  }

}

With this setup, you can take a number input and automatically convert it to a string before assigning it as the id.

For instance,

If we use the given Person definition:

class Person {
  private _id: string

  get id() {
    return this._id;
  }

  set id(val) {
    // Handling both number and string values
    this._id = typeof val === 'number' ? `${val}` : val
  }

}

You can now assign numbers to the id property and they will be automatically converted to strings.

const myPerson: Person = new Person();
myPerson.id = 2
typeof myPerson.id // string

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

Creating a new endpoint within the Angular2 framework using typescript

I am brand new to Angular2 and I would like to streamline my API endpoints by creating a single class that can be injected into all of my services. What is the most optimal approach for achieving this in Angular2? Should I define an @Injectable class sim ...

Inheriting an Angular 5 class with injected dependencies

I recently defined a new class @Injectable FooService { constructor(private _bar:BarService){ } } Then I decided to extend it in the following way @Injectable ExtFooService extends FooService { constructor(private _bar:BarService){ ...

What is the best way to invoke a function with multiple parameters in TypeScript?

I have a function that manipulates a specified query string, along with another version that always uses window.location.search. Here is the code snippet: class MyClass { public changeQuery(query: string; exclude: boolean = true; ...values: string[]): st ...

undefined event typescript this reactjs

I have come across the following TypeScript-written component. The type definitions are from definitelytyped.org. I have bound the onWheel event to a function, but every time it is triggered, this becomes undefined. So, how can I access the referenced el ...

Having trouble accessing functions in Typescript when importing JavaScript files, although able to access them in HTML

Recently, I started incorporating TypeScript and React into my company's existing JavaScript code base. It has been a bit of a rollercoaster ride, as I'm sure many can relate to. After conquering major obstacles such as setting up webpack correc ...

Using .map() with a union type of string[] or string[][] results in a syntax error

interface Props { data: string[] | string[][]; } function Component({ data }: Props) { return data.map(v => v); } map() is causing an error: The expression is not callable. Each member of the union type '((callbackfn: (value: string, in ...

Verifying the accuracy of a React Component in interpreting and displaying a path parameter

I have the following React/Typescript component that is functioning correctly. However, I am struggling to write a test using testing-library. My goal is to verify that it properly receives the level parameter and displays it on the page: import React from ...

Issue: Unable to ascertain a GraphQL input type in Nestjs + Graphql + Typeorm configuration

I'm currently exploring Nestjs, Graphql, and Typeorm for the first time. However, I've encountered a roadblock where I am unable to resolve an issue. Specifically, I'm using the @ManyToOne relationship to connect food with a user, but I keep ...

Interface with several generic types

In an attempt to create a parser that can parse data fields and convert them into a complete form for display purposes, the fields property plays a crucial role. This property will define each field in a JSON data array that the client receives from the ur ...

React is not displaying the most recent value

During the initial rendering, I start with an empty array for the object date. After trying to retrieve data from an influxDB, React does not re-render to reflect the obtained results. The get function is being called within the useEffect hook (as shown in ...

Getting a date object that is three months prior to the current date in Typescript

I need to retrieve the date object that is 3 months before the current date by using the following code snippet: toDate = new Date(); fromDate = this.toDate.getMonth() - 3; The issue I am facing is that the variable fromDate only contains a number, but I ...

How to remove a specific type from a generic type in Typescript without using Exclude<>?

I am looking for a solution to prevent my function from working with Moment objects when storing values in local storage. Currently, the function dynamically stringifies and stores values, but I want to exclude Moment objects from being processed. Here is ...

Acquiring the download link for Firebase Storage in Angular 2+ technology

reference: AngularFireStorageReference; task: AngularFireUploadTask; uploadState: Observable<string>; uploadProgress: Observable<number>; downloadLink: Observable<string>; beginUpload(event) { const id = Math.floor(Math.random() * 1000 ...

Encountering unexpected null values post-service invocation in Angular 2

I have encountered an issue in Angular 2 where a variable is returning undefined. The problem arises when a function calls a service to initialize a variable, which is then used in another function to make a get HTTP request. However, the get request fails ...

Ways to transfer information from the parent component while the component is repeatedly utilized on the page

Consider the following situation within Angular 6: There is one upload component that is being utilized twice on the same page. By clicking the add button on any upload component using a behavior subject, data specific to that upload component can be obt ...

The configuration object is invalid. Angular has initialized Webpack using a configuration object that does not align with the API schema

When attempting to run the angular application with "ng serve -o", I encountered an error message stating "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema." Prior to this issue, "n ...

React Native (or React) utilizes separate TypeScript modules to detect and respond to style adjustments for dark mode

Objective: Add a dark mode feature to a react native application. A brief overview of the system: File structure: Profile.ts ProfileCss.ts constants.ts In my app, I've organized styles in separate .ts files and exported them as modules to keep them ...

Is it feasible to evaluate a Typescript method parameter decorator at request time in a nodejs+nestjs environment rather than just at build time?

Looking to simplify my handling of mongodb calls with and without transactions in a single service method by writing a decorator. This would help eliminate the repetition of code and make things more efficient. Key points for usage: • Service class has ...

Error encountered in Typescript: SyntaxError due to an unexpected token 'export' appearing

In my React project, I encountered the need to share models (Typescript interfaces in this case) across 3 separate Typescript projects. To address this, I decided to utilize bit.env and imported all my models to https://bit.dev/model/index/~code, which wor ...

Creating a custom Typescript type by leveraging Javascript variables as the key identifiers

Picture a Typescript library that serves as a database interface, giving developers the ability to specify record attributes/columns/keys to be retrieved from the database. Is it feasible to return a type that includes the keys specified by the developer? ...