使用 MobX 在 Typescript 中找不到名称
Cannot find name in Typescript with MobX
我创建了简单的 MobX 商店:
import { observable, action, computed } from "mobx"
interface UserInterface {
login: string
email: string
password: string
}
class User {
@observable users: UserInterface[] = []
@action addUser = (newUser: any) => {
this.users.push(newUser)
}
@action logMe = () => {
console.log("MobX works!");
}
@computed get userCount() {
return this.users.length
}
}
export const UserStore = new User()
这是使用该商店数据的组件的开头:
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles"
import { inject, observer } from "mobx-react"
import { UserStore } from "../../../stores/user-store"
interface RegisterFormProps extends WithStyles<typeof RegisterFormStyles> {
userStore?: UserStore
}
@inject("userStore")
@observer
class LoginForm extends React.Component<RegisterFormProps> {
我在 userStore?: UserStore
部分有一个 tslint 错误。它抛出错误:Type error: Cannot find name 'UserStore'. TS2304
。 class 的路径是正确的。如果我将类型从 UserStore 更改为 any
它可以工作,但我想避免使用 any
类型。
@编辑。解决方案是在 MobX 存储文件的末尾包含以下行:
const UserStore = new User();
export { UserStore }
export const UserStore = new User()
表示您正在导出变量 UserStore
并且变量不能用作类型(但 classes 可以)。您必须导出 class UserStore
在界面中使用它 userStore?: User
你试过了吗?
const UserStore = new User();
export { UserStore }
我创建了简单的 MobX 商店:
import { observable, action, computed } from "mobx"
interface UserInterface {
login: string
email: string
password: string
}
class User {
@observable users: UserInterface[] = []
@action addUser = (newUser: any) => {
this.users.push(newUser)
}
@action logMe = () => {
console.log("MobX works!");
}
@computed get userCount() {
return this.users.length
}
}
export const UserStore = new User()
这是使用该商店数据的组件的开头:
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles"
import { inject, observer } from "mobx-react"
import { UserStore } from "../../../stores/user-store"
interface RegisterFormProps extends WithStyles<typeof RegisterFormStyles> {
userStore?: UserStore
}
@inject("userStore")
@observer
class LoginForm extends React.Component<RegisterFormProps> {
我在 userStore?: UserStore
部分有一个 tslint 错误。它抛出错误:Type error: Cannot find name 'UserStore'. TS2304
。 class 的路径是正确的。如果我将类型从 UserStore 更改为 any
它可以工作,但我想避免使用 any
类型。
@编辑。解决方案是在 MobX 存储文件的末尾包含以下行:
const UserStore = new User();
export { UserStore }
export const UserStore = new User()
表示您正在导出变量 UserStore
并且变量不能用作类型(但 classes 可以)。您必须导出 class UserStore
在界面中使用它 userStore?: User
你试过了吗?
const UserStore = new User();
export { UserStore }