使用参数(computedFn)和TypeScript计算的Mobx-这是什么?

问题描述 投票:0回答:1

以下示例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'隐式具有类型'any',因为它没有类型注释。ts(2683)

此容器的外部值是'this'的阴影。

将tsconfig的noImplicitThis设置为false可以解决此问题,但我的目的是将noImplicitThis设置为true

有什么想法吗?谢谢!

reactjs typescript mobx mobx-react
1个回答
0
投票

注入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))
  })
}
© www.soinside.com 2019 - 2024. All rights reserved.