【问题标题】:Mobx Computed with Arguments (computedFn) and TypeScript - what's this?使用参数 (computedFn) 和 TypeScript 计算的 Mobx - 这是什么?
【发布时间】:2020-04-03 11:01:00
【问题描述】:

以下示例 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' 因为它没有类型 annotation.ts(2683)

'this' 的外部值被此容器遮蔽。

将 tsconfig 的 noImplicitThis 设置为 false 将解决此问题,但我的意图是将 noImplicitThis 设置为 true

有什么想法吗?谢谢!

【问题讨论】:

    标签: reactjs typescript mobx mobx-react


    【解决方案1】:

    注入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))
      })
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 2022-09-27
      • 2018-09-16
      • 1970-01-01
      相关资源
      最近更新 更多