以下示例https://mobx.js.org/refguide/computed-decorator.html使用 TypeScript 会引发错误。
// Parameterized computed views:
// Create computed's and store them in a cache
import { observable } from "mobx"
import { computedFn } from "mobx-utils"
class Todos {
@observable todos = []
getAllTodosByUser = computedFn(function getAllTodosByUser(userId) {
return this.todos.filter(todo => todo.user === userId))
})
}
'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
An outer value of 'this' is shadowed by this container.
将 tsconfig 的 noImplicitThis
设置为 false 可以解决此问题,但我的目的是将 noImplicitThis
设置为 true
。
有什么想法吗?谢谢!
最佳答案
注入(inject) this: Todos
将修复它。 TypeScript 不会提示,并且 this
将被正确键入。请注意,TS 编译器在编译为 JavaScript 时会删除 this
参数。
// Parameterized computed views:
// Create computed's and store them in a cache
import { observable } from "mobx"
import { computedFn } from "mobx-utils"
class Todos {
@observable todos: ITodo[] = []
getAllTodosByUser = computedFn(function getAllTodosByUser(this: Todos, userId: ITodo[]) {
return this.todos.filter(todo => todo.user === userId))
})
}
关于reactjs - Mobx 使用参数计算 (compulatedFn) 和 TypeScript - 这是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59264167/