mobxjs / mobx-state-tree

Full-featured reactive state management without the boilerplate
https://mobx-state-tree.js.org/
MIT License
6.9k stars 639 forks source link

When observe() a MST node's primitive property, TypeScript get the wrong type of oldValue & newValue #2105

Open songzhenqi opened 8 months ago

songzhenqi commented 8 months ago

Bug report

Sandbox link or minimal reproduction code

import { observe } from "mobx"
import { types } from "mobx-state-tree"

const Model = types
    .model('Model', {
        name: types.string,
    })
    .actions((self) => ({
        setName(newName: string) {
            self.name = newName
        },
    }))

const model = Model.create({
    name: "John",
})

observe(model, 'name', (change) => {
    if (change.type === 'update') {
        console.log(`observe storedValue, ${change.oldValue?.storedValue}, ${change.newValue?.storedValue}`)
        console.log(change.oldValue)
        console.log(`observe, ${change.oldValue}, ${change.newValue}`)
    }
})

model.setName("Dave");

Describe the expected behavior Typescript inferring the oldValue & newValue as ScalarNode

Describe the observed behavior TypeScript inferring the oldValue & newValue as string

image

chakrihacker commented 8 months ago

The store value is of type any because of references. This is from the Code // usually the same type as the value, but not always (such as with references)

Maybe we need to cast the Model type if it's not a reference