Reputation: 542
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:
TypeError: currentUser.getID is not a function.
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:
componentDidMount() {
const currentUser: User = this.props.currentUser;
this.setState({ loading: true });
const currentUserID = currentUser.getID(); <---- FAILS HERE
const currentUserIDString = currentUserID.toString();
}
}
Upvotes: 3
Views: 8665
Reputation: 187044
TypeError: currentUser.getID is not a function.
This error means that currentUser
is some value which does not have a getID
method on it. Your class is fine, so something is wrong with the value of currentUser
and not the User
class.
It appears that currentUser
is a plain javascript object, and not an instance of your class.
const currentUser: User = this.props.currentUser;
This line does not make currentUser
an instance of User
, it merely a type hint for 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. If you never call new User()
then you do not have an instance of User
, you just have a plain object.
Upvotes: 1