Change the type of an object to a different type

Within my class, I have set the type of range to IntervalRange.

export class Test {range: IntervalRange;}

Then, in the parent class, I initialize the value:

export class TestInitializer {
Create(){
    return <Test>{
        range: IntervalRange.initialize(Database.GetByName('MONTH').id};
}

InitializeElement() {
  let test = <Test>JSON.parse(JSON.stringify(configuration));
  return test;
}

In another component, I use this as:

@Input() range: IntervalRange;

However, when calling the function range.getRange();, an error is thrown:

ERROR TypeError: this.range.getRange is not a function

This is puzzling, as it indicates that range is an Object when it should be an IntervalRange.

I attempted using as IntervalRange and <IntervalRange> range but nothing resolved the issue. How can this be fixed?

Update: let type = typeof(this.range); outputs "object"

Here is the method:

ngOnChanges() {
if (this.range) {
  let type = typeof(this.range);
  let ddd = this.range.getRange(); //<----- this is where I encounter the error
}

Answer №1

When using typecasting, it's important to understand that Typescript does not actually exist at runtime. This means that calling JSON.parse may not return a valid Test instance due to serialization issues with methods. To avoid runtime failures, consider constructing a new Test instance and loading the serialized data into it instead of just typecasting.

Answer №2

Utilizing TypeScript for type casting (<A>tmp or tmp as A) :

  • Performs structural type compatibility checking → not available when source data is of type any.
  • Lacks a runtime equivalent → TypeScript types may match, but actual runtime types can vary (e.g., object literal vs. class instance).

When receiving data from an insecure/external origin like JSON.parse() or a WebAPI call, it typically involves a DTO (data transfer object), usually with the type any. Typecasting in TypeScript under such circumstances can be risky.

To ensure safe casting, employ a mapping function that converts the DTO to a "domain model" class, ensuring the returned value is a legitimate class instance.

  • Object.assign(new IntervalRange(), this.range)
    (as mentioned in a comment) fulfills this requirement.
  • For greater strictness, consider a "field by field mapping":
    this.a = range.a; this.b = range.b; ...)
    .

Both approaches are best encapsulated within a function: whether through the class constructor, a static factory method within the class, or an external function in the same module.

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

modify the final attribute's value

Hello I've been using skrollr js to create a parallax website. However, the issue arises when determining the section height, as it depends on the content within. My goal is to locate the last attribute and adjust the number value based on the section ...

Examining the function of a playwright script for testing the capability of downloading files using the window.open

Currently, we are working on a project that uses Vue3 for the frontend and we are writing tests for the application using Playwright. Within our components, there is a download icon that, when clicked, triggers a handler to retrieve a presigned URL from S3 ...

Obtain the location of the image source from a text file within an HTML document

I need to create a slideshow displaying a sequence of images. The path to these images will be stored in a text file. How can I read the image paths from the text file? Currently, I have hardcoded code like the example below: <div class="mySlides fade" ...

Tips on saving Firebase Storage image url in Firebase database?

How do I store the URL of an image uploaded to Firebase Storage in Firebase Database? When executing the code below, I encounter the following error: Uncaught (in promise) FirebaseError: Function DocumentReference.set() called with invalid data. Unsuppor ...

When refreshing the page, the authentication token set in the Vuex store using axios in Nuxt.js/Vue.js gets reset

Here is the code snippet I am using to manage login, logout, user retrieval, and token setting for all axios requests as an auth header. While this code works perfectly during client-side rendering - such as logging in, storing the token in cookies, etc. ...

Using React Typescript to create a button component with an attached image

I am currently utilizing React with Typescript. How can I incorporate an image into my button? I've attempted to do so without any errors, but the button appears blank. What's the best way to style my button element using Emotion CSS in this ...

What's the best way to implement satisfies with a generic type?

In my development process, I am working with components that have default values combined with props. To streamline this process, I created a single function for all components: export function getAssignProps <T extends {}>(propsMass:T[]){ return ...

Glitch found in Safari involving innerText of elements

Hey everyone, I posted this question not too long ago but now I have some images to share regarding the issue with Safari. When checking the console in Safari, the following text is displayed: <div id="rot3posDisp" class="rotDisp">C</div> Ho ...

Customizing Ext JS/Sencha Chart framework based on certain conditions

As someone who is new to Ext JS and Sencha charts, I have encountered a challenge with one of the charts in our application. Specifically, I needed to hide the dashes on the X-Axis of that particular chart. Our application is built using Ext JS version 5.1 ...

Typescript having issues compiling to commonjs/es2015 accurately

I currently have Node v14.5.0 installed and I'm using ts-node-dev in my development environment However, I am encountering an error every time I try to compile to JS. Initially, I attempted with the following tsconfig: "target": "es5& ...

Next JS Event Listener Failing to Detect Scroll Events

Currently, I am attempting to change the state and display a shadow in the navigation bar when the user scrolls, but for some reason it is not detecting the event. I am working with nextJS 13 and tailwind css. const [shadow, setShadow] = useState(false) ...

Highcharts - running out of space for tooltips – what's the solution? Show only the tooltip for the series being hovered over, or adjust the layout to accommodate all tooltips

I am facing an issue where not all of the tooltips on my chart are displayed when hovering, as shown in the image provided. Specifically, the tooltip for the green series is missing. https://i.sstatic.net/QcbWV.png Upon researching, I discovered that Hig ...

Trouble with invoking a function within a function in Ionic2/Angular2

Currently, I am using the Cordova Facebook Plugin to retrieve user information such as name and email, which is functioning correctly. My next step is to insert this data into my own database. Testing the code for posting to the database by creating a func ...

An undefined variable in Angular 2's evaluation

I am currently working with the following code: @ViewChild('MondayPicker') MondayPicker; @ViewChild('TuesdayPicker') TuesdayPicker; @ViewChild('WednesdayPicker') WednesdayPicker; @ViewChild('ThursdayPicker') Thursda ...

No results are being returned by karma.js after setting up a basic "karma init" configuration

Currently, I am working through the tutorial "Introduction to Karma" on egghead.io which can be found here. To set up Karma on Windows, I followed these steps: > npm install --g karma-cli > npm install karma karma-jasmine karma-chrome-launcher --sav ...

If the FedEx function does not receive a payment, it will need to return a value of Payment Required

I am struggling with understanding functions, parameters, and arguments in JavaScript as I am new to it. My goal is to have a function that returns different values based on the payment amount. If no payment is passed, it should return "Payment Required", ...

Tips for Simplifying Complex Switch Cases with Object Literals in TypeScript

I have a unique situation where I need to switch between two functions within an object literal. One function takes two numerical arguments, "A" and "B", while the other function only takes a single string argument, "C". My TypeScript code showcases my di ...

Managing data in Vuex by updating it from a child component using $emit

I'm currently working on a Vue app that has the capability to randomize a title and subtitle or allow users to manually edit these values using a custom input component. The challenge I'm facing is updating the parent component and state to refle ...

Struggling to pass command line arguments to index.ts with yarn?

My objective is to pass arguments through the command line using yarn start to index.ts. "scripts": { "start": "tsc-watch --onSuccess \"ts-node --pretty -r tsconfig-paths/register' src/index.ts\"", } When I attempt something like: yarn ...

I am having trouble with updating an array in React useState. Every time I try to make changes, it keeps reverting back to the initial state. What could

My current task involves managing a state array called monthlyIncidents, which contains 12 numbers that need to be updated under certain conditions. I attempted to update the elements by copying the array, modifying the specific element, and then updating ...