gpt4 book ai didi

javascript - typescript 不打字

转载 作者:行者123 更新时间:2023-12-03 03:38:35 25 4
gpt4 key购买 nike

我正在尝试从处于 react 状态的对象调用函数

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

但它只是给出了一个错误this.state.currentUser.rankUp is not a function。如果我创建一个新的用户对象,但它确实让我调用所述函数。即使我尝试将其转换为用户: var user:User = this.state.currentUser as User 然后调用它给出的函数同样的错误。我尝试打印类型,即使在转换它时,它也会返回为 object 而不是 User

到目前为止,我设法让它工作的唯一方法是 user.rankUp = (new User("a")).rankUp; 尽管它有效,但感觉它不正确.

编辑:

User.rankUp 定义为:

rankUp(){
this.rank +=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 没有类型转换。它有类型断言: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.

所以回答你的问题:

Typescript not typecasting

因为没有类型转换。 🌹

关于javascript - typescript 不打字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45741251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com