打字稿类中的方法给出错误“不是函数". [英] Method in typescript class give error "is not a function"

查看:79
本文介绍了打字稿类中的方法给出错误“不是函数".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular2 Web应用程序上工作.我在打字稿中创建了一个简单的类:

I work on Angular2 web application. I created a simple class in typescript:

export class User {
    firstName: string;
    lastName: string;

    nominative() : string {
        return this.lastName + " " + this.firstName;
    }
}

当我在类型为User的对象上调用nominative时,出现此错误:Error in :0:0 caused by: user.nominative is not a function.

When i call nominative on object of type User I receive this error: Error in :0:0 caused by: user.nominative is not a function.

我在AppComponent类中调用该函数:

export class AppComponent implements OnInit {
    name: string = "";

    ngOnInit() : void {
        let user = JSON.parse(sessionStorage.getItem("User")) as User;
        if (user) {
            this.name = user.nominative();
        }
    }
}

我已经尝试通过这种方式使用lambda表达式:

I already tried to use lambda expression in this way:

nominative = () : string => { ... }

但是什么都没有改变.问题只在这个班上,所以我在做什么错了?

But nothing change. The problem is only in this class, so what am I doing wrong?

推荐答案

as User仅告诉编译器可以安全地假定该值的类型为User,但对运行时没有任何影响,它将没有任何方法,因为方法未随JSON传递.

as User only tells the compiler that it's safe to assume that the value is of type User, but doesn't have any effect on runtime and it won't have any methods because methods are not passed with JSON.

您需要

let user = new User(JSON.parse(sessionStorage.getItem("User")));

以获取实际的User实例.您将需要创建一个构造函数,将JSON中的值分配给类似

to get an actual User instance. You would need to create a constructor that assigns the values from JSON to fields like

class User {
  ...
  constructor(json:any) {
    this.firstName = json.firstName;
    this.lastName = json.lastName;
  }

这篇关于打字稿类中的方法给出错误“不是函数".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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