简体   繁体   English

类型错误:<...> 不是函数

[英]TypeError: <...> is not a function

So, I'm running into a problem and I'm not sure exactly how to resolve it.所以,我遇到了一个问题,我不确定如何解决它。 After reading through the ES6 doc's I think I have this set up correctly, yet when I call <UserInstance>.getID() I get the error:阅读完 ES6 文档后,我认为我的设置正确,但是当我调用<UserInstance>.getID()出现错误:

TypeError: currentUser.getID is not a function.类型错误:currentUser.getID 不是函数。

I know this may be a duplicate but in the other questions I've seen answer similar questions, none of them have allowed me to resolve this issue.我知道这可能是重复的,但在我看到的其他问题中回答了类似的问题,但没有一个允许我解决这个问题。

Here's my class definition:这是我的类定义:

import { v4String } from "uuid/interfaces";
class User {
    private id!: v4String;
    constructor() {
        this.getID = this.getID.bind(this);
        this.setID = this.setID.bind(this);
    }
    getID = () => this.id;
    setID = (id: v4String) => this.id = id;
}
export default User; 

I'm pretty sure I have the class set up, but is there something I'm missing with the arrow function?我很确定我已经设置了课程,但是箭头函数有什么我遗漏的吗? It doesn't seem to matter if I set it up with the arrow function syntax, or set it up like如果我用箭头函数语法设置它,或者像这样设置它似乎并不重要

getID() {
   return this.id
}

Here's the code that's calling it, currentUser is provided by a context provider and injected into the props using a Higher Order Component:这是调用它的代码,currentUser 由上下文提供程序提供,并使用高阶组件注入到道具中:

componentDidMount() {
        const currentUser: User = this.props.currentUser;

        this.setState({ loading: true });

        const currentUserID = currentUser.getID(); <---- FAILS HERE
        const currentUserIDString = currentUserID.toString();

        }
    }

TypeError: currentUser.getID is not a function.类型错误:currentUser.getID 不是函数。

This error means that currentUser is some value which does not have a getID method on it.这个错误意味着currentUser是一些没有getID方法的值。 Your class is fine, so something is wrong with the value of currentUser and not the User class.你的课程很好,所以currentUser的值有问题,而不是User类。

It appears that currentUser is a plain javascript object, and not an instance of your class.看来currentUser是一个普通的 javascript 对象,而不是您的类的实例。

const currentUser: User = this.props.currentUser;

This line does not make currentUser an instance of User , it merely a type hint for typescript.这一行不会使currentUser成为User的实例,它只是 typescript 的类型提示。 And it is a type hint that is incorrect.这是一个不正确的类型提示。

Somewhere (where is up to you) you need to call new User() in order to be able to use the methods that you have defined on your user class.在某个地方(取决于您),您需要调用new User()以便能够使用您在用户类中定义的方法。 If you never call new User() then you do not have an instance of User , you just have a plain object.如果你从不调用new User()那么你就没有User的实例,你只有一个普通对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM