为什么从JSON文字转换为不包含函数的类型 [英] Why does casting from JSON literal to type not include functions

查看:164
本文介绍了为什么从JSON文字转换为不包含函数的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的模型类:

export class Task {

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

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

以及检索任务的服务:

export class TaskService {

    constructor(private _http: Http) {}

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

当我尝试调用 completeTask 任务上的函数我收到错误信息:

When I then try to call the completeTask function on the task I get the error message:


TypeError:task.completeTask()不是函数

TypeError: task.completeTask() is not a function

当我将JSON文字对象转换为任务时,我得到相同的结果。

I get the same result when I cast a JSON literal object to a task.

let task: Task = <Task>{ name: "Make some coffee" }
task.completeTask(); // Results in error

我做错了什么?如何确保包含函数?

Am I doing something wrong? How can I make sure functions are included?

推荐答案

事实上,当你施放时,你实际上没有一个实例你输入的类型。您只声明一个文字形式的对象而不是任务的实例。

In fact when you cast, you don't really have an instance of the type you cast. You only declare an object with the literal form not an instance of task.

如果它只是TypeScript提供的方式来检查铸造对象是否遵循该类型的结构。但它只是在运行时才出现在设计/编译时。

If it's just a way provided by TypeScript to check that the casted object follows the structure of the type. But it's not something at runtime only at design / compile time.

如果你想能够使用你需要的类型的方法来实例化一个新的对象基于content:

If you want to be able to use methods of the type you need to instantiate a new object based on the content:

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;
        });
}

有关详细信息,请参阅此问题:

See this question for more details:

  • angular2 map data as specific object type

修改

根据@ ssube的评论,您可以声明任务类,如下所示:

Following the @ssube's comment you could declare the Task class like this:

export class Task {
  (...)

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

  (...)
}

这样实例化会更容易:

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

这篇关于为什么从JSON文字转换为不包含函数的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆