reactjs - Mobx Computed พร้อมอาร์กิวเมนต์ (computedFn) และ TypeScript - นี่คืออะไร?
ตัวอย่างดังต่อไปนี้ 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' ถูกซ้อนด้วยคอนเทนเนอร์นี้
การตั้งค่า noImplicitThis ใน tsconfig เป็น false จะช่วยแก้ไขปัญหานี้ได้ แต่ความตั้งใจของฉันคือการเก็บ noImplicitThis ไว้เป็น true
มีไอเดียไหม? ขอบคุณ!
คำตอบ #1
การฉีด this: Todos จะช่วยแก้ปัญหา TypeScript จะไม่แสดงข้อผิดพลาด และ this จะถูกพิมพ์ชนิดอย่างถูกต้อง โปรดสังเกตว่า ตัวคอมไพเลอร์ TS จะลบพารามิเตอร์ this เมื่อคอมไพล์เป็น 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))
})
}
