Why aren't functions included when casting from a JSON literal to a specific type?

In my model class, the structure looks like this:

export class Task {

    public name: string;
    public status: string = "todo";

    public completeTask(): void {
        this.status = "done";
    }   
}

There is also a service responsible for retrieving tasks:

export class TaskService {

    constructor(private _http: Http) {}

    public getTask(): Observable<Task> {
        return this._http
            .get("url")
            .map(res => res.json().data as Task)
    }
}

However, when attempting to execute the completeTask function on the task object, an error message occurs:

TypeError: task.completeTask() is not a function

The same error is encountered when trying to convert a JSON literal object to a task instance.

let task: Task = <Task>{ name: "Make some coffee" }
task.completeTask(); // This line triggers an error

I am wondering if I made a mistake somewhere. How can I ensure that functions are properly included in my task objects?

Answer №1

When performing a cast in TypeScript, you are not actually creating an instance of the type being cast to. Instead, you are simply declaring an object with the expected structure, not an actual instance of that type.

The purpose of casting in TypeScript is to ensure that the object being cast follows the structure defined by the type. This check occurs during design and compile time, rather than at runtime.

If you need to access methods or properties of a specific type, you will have to instantiate a new object that matches the required structure:

public getTask(): Observable<Task> {
    return this._http
        .get("url")
        .map(res => {
          let content = res.json().data;
          let task = new Task();
          task.name = content.name;
          task.status = content.status;
          return task;
        });
}

For more information on this topic, you can refer to the following question:

Additional Note:

As suggested by @ssube, you could define the Task class with a constructor that accepts an object with the required properties:

export class Task {
  (...)

  constructor(obj:{name:string, status:string}) {
    this.name = obj.name;
    this.status = obj.status;
  }

  (...)
}

This approach simplifies the instantiation process:

public getTask(): Observable<Task> {
    return this._http
        .get("url")
        .map(res => new Task(res.json().data));
}

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

Parsing nested json objects in an angular application

I'm trying to work with a complex nested JSON structure and I need to extract and display the data in HTML. The JSON data I have looks like this: { "Test Data": [ { "First Test": { "Design Name": "testname", "Output": "1" ...

Trigger a random tune when hovering the mouse

I need help figuring out how to make a fixed image on my page trigger a random sound track when hovered over. The sound could be one of five different tracks. Here is the HTML for my image: <img src="images/Airplane.png" class="Airplane-photo"> Bel ...

What is the best way to create a delay in user hover activation before triggering a slideDown

In my current code snippet, I have implemented the functionality to perform a slideDown action when a user hovers over an element. However, I would like this slide down effect to only occur if the user has hovered for at least 2 seconds. If the user does n ...

Tips for passing parameters in the $http GET request to transmit information from a dropdown menu using AngularJS

In the modal window I have for creating a new object, there are three forms: 1) a simple input to create "Name"; 2) A dropdown with "Types"; 3) A dropdown with "Ids". The issue arises when trying to send the data after filling out all the forms. An error o ...

Error: The variable $traceurRuntime has not been defined in the AngularJS application

Currently, I am utilizing [gulp-traceur][1] to convert es6 to js within my angularjs application (version 1.x). However, when attempting to compile a for loop, an error occurs: ReferenceError: $traceurRuntime is not defined It appears that I may need to ...

Steps to resolve the Uncaught SyntaxError: Unexpected token o in JSON at position 1 issue

$.ajax({ url: "/url/url.ajax?length=100000&startDate=2018-07-01", method: "get", dataType: "json", success: function (jdata) { var jsonData=JSON.parse(jdata.data); ...

JavaScript Logic to Check if an Element is Hidden

I'm having trouble figuring out how to close an element when another element collapses. I've searched for solutions without success. My structure is updated using Bootstrap and JavaScript, but it doesn't function as expected. Specifically, ...

What is the most efficient method for transforming JSON data into an object using JavaScript?

Currently, my method in JavaScript involves utilizing the eval function to transform JSON data retrieved from the server into an object. eval ("myObject="+data); I have received feedback that using eval is considered 'evil' and could potentiall ...

Is the table state not supported for reordering columns within the table component?

I am currently using version 12.2.3 of PrimeNg along with the p-table component. I have successfully managed to resize and reorder columns in the table. However, I am facing an issue when trying to save the table state. Once I enable the feature to save th ...

Establishing SAPUI5 Odata Connection with Server

Hello, I have a question. Is it possible to access OData data without using a cloud connector? For example, can I retrieve the data directly from a URL like https://serverip:port/sap/opu/odata/sap/? When I try accessing it through the browser, I am able to ...

Transform the HTML content into a JSON format file

I'm currently developing an online marketplace and trying to convert all product information like name, price, and description into json format. I have a sample code featuring a selection of products displayed in rows. <div class='cakes'& ...

Javascript Macros for Mastering Excel

My goal is to use Javascript macros to handle excel spreadsheets instead of the standard VBA. I have found a way to run javascript code through VBA, as shown below: 'javascript to execute Dim b As String b = "function meaningOfLife(a,b) {return 42;}" ...

Having trouble running npm start with Express generator

After installing Express Generator according to the instructions on the website, I encountered an issue when trying to run npm start. My Windows system has npm 6.4.1 and node v10.15.3 installed. > [email protected] start C:\Users\ONLINEW ...

Tips on attaching the main element of a partial view

I have a scenario in my ASP.NET MVC project where I need to render a partial view once in the main view, and then upon clicking the add button, I want to append the entire partial view to the form. However, when I click add, only the child element is added ...

Loop through an icon in Angular 2 until a specific condition is met

Currently, I am in the process of developing my portfolio website using Angular 2 and I want to incorporate a skill matrix. For testing purposes, I am using a square provided by font-awesome as an example. <tbody *ngFor="let skill of skills"> <tr ...

How can I connect the Bootstrap-datepicker element with the ng-model in AngularJS?

Below is the html code for the date field : <div class='form-group'> <label>Check out</label> <input type='text' ng-model='checkOut' class='form-control' data-date-format="yyyy-mm-dd" plac ...

What is the process of retrieving a dynamic array value based on checkbox selection in AngularJS?

I need help with a situation where I am trying to use Angular to get the value of a checkbox. I have a Java object on my HTML page and when a user checks an individual box, that single value should be added to my array. If the user checks 'Select All& ...

"Embedding PHP code within HTML tags, which is then embedded within

Running into an issue within a while loop... echo 'var contentString = '<div id="content" > <div id="bodyContent"> <p>' + $row[name]+ '</p> ...

Succession of Mongoose queries

One interesting feature of my model is the ability to chain queries like find(), limit(), and skip(). However, there arises a question: How can I apply the limit or skip function to the output of Model.find() if the returning value does not inherently cont ...

What is the process for transferring items using ref ObjectId's?

https://i.sstatic.net/pi6js.pngI'm currently in the process of developing a small personal betting website. I have successfully created Arrays of ObjectId's within each collection that reference one another. However, I am facing challenges when i ...