首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用参数(computedFn)和TypeScript计算的Mobx --这是什么?

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

Stack Overflow用户
提问于 2019-12-10 09:37:01
回答 1查看 1.8K关注 0票数 2

下面的示例https://mobx.js.org/refguide/computed-decorator.html使用TypeScript引发错误。

代码语言:javascript
复制
// 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

有什么想法吗?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-10 10:06:02

注射this: Todos可以解决这个问题。TypeScript不会抱怨,this将被正确地键入。注意,TS编译器在编译到JavaScript时将移除JavaScript参数。

代码语言:javascript
复制
// 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))
  })
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59264167

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档