-
My English is not good, but i want improve docs =) Index: docs/tips/typescript.md
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- docs/tips/typescript.md (revision 8f3706d08e35f600d12a658ae1ecb19a12f85638)
+++ docs/tips/typescript.md (date 1607213900937)
@@ -68,6 +68,29 @@
#### Typing `self` in actions and views
+You can help typescript with manually type self:
+
+```typescript
+const Todo = types
+ .model({
+ title: "hello"
+ })
+ .actions((self: ITodo) => ({
+ get upperProp(): string {
+ return self.prop.toUpperCase()
+ },
+ get twiceUpperProp(): string {
+ return self.upperProp + self.upperProp // Compile error: `self.upperProp` is not yet defined
+ }
+ }))
+
+interface ITodo extends Instance<typeof Todo> {}
+interface ITodoSnapshotIn extends SnapshotIn<typeof Todo> {}
+interface ITodoSnapshotOut extends SnapshotOut<typeof Todo> {}
+```
+
+Explain the problem:
+
The type of `self` is what `self` was **before the action or views blocks starts**, and only after that part finishes, the actions will be added to the type of `self`.
Sometimes you'll need to take into account where your typings are available and where they aren't. The code below will not compile: TypeScript will complain that `self.upperProp` is not a known property. Computed properties are only available after `.views` is evaluated.
@@ -111,7 +134,7 @@
get upperProp(): string {
return self.prop.toUpperCase();
},
- }))
+ })
.views(self => ({
get twiceUpperProp(): string {
return self.upperProp + self.upperProp;
@@ -134,7 +157,7 @@
}
}
return views
- }))
+ }) NOTE: the last approach will incur runtime performance penalty as accessing such computed values (e.g. inside
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
reference to itself, typescript will crash =(( |
Beta Was this translation helpful? Give feedback.
reference to itself, typescript will crash =((