0

I'm trying to call a function from an object in my react state

//currentUser is of type User
this.state.currentUser.rankUp()

but it just gives an error this.state.currentUser.rankUp is not a function. If I create a new user object though it does let me call said function.Even if I try casting it as user: var user:User = this.state.currentUser as User then calling the function it gives the same error. I tried printing the type and even when casting it it returns as object not User

The only way I've managed to get it to work so far is user.rankUp = (new User("a")).rankUp; which feels like its incorrect even though it works.

EDIT:

User.rankUp is defined as:

rankUp(){
    this.rank +=1;
}
5
  • Should be this.state.currentUser.rankUp, () means its a function mate. Commented Aug 17, 2017 at 17:12
  • 2
    as Thing is a hint, not a conversion, it just tells TS you know what the type of the value will be (and, in this case, you were wrong). The solution you have is nearly correct, TypeScript won't convert a generic object (e.g. from JSON) to an instance without you newing one up. But you don't have to patch the one thing, try user = new User(user.whatever); instead. Commented Aug 17, 2017 at 17:13
  • Well, how is rankUp defined? Commented Aug 17, 2017 at 17:13
  • can you post the User Class Commented Aug 17, 2017 at 18:20
  • You need to post more code. My assumption now is that the this.state.currentUser is not what you think it is. Do a console.log(this.state.currentUser) and look at the prototype of the object. Are you sure it's a User? We need to see more of your code to help you. Commented Aug 18, 2017 at 0:02

1 Answer 1

1

Even if I try casting it as user: var user:User = this.state.currentUser as User then calling the function it gives the same error.

TypeScript doesn't have type casting. It has type assertion : https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html

The reason why it's not called "type casting" is that casting generally implies some sort of runtime support. However type assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed.

So to answer your question:

Typescript not typecasting

Because there is no type casting. 🌹

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.