mobx-state-tree
mobx-state-tree copied to clipboard
Typesafety loophole: can pass garbage to SomeModel.create
I am able to pass a snapshot in invalid shape to create method, and neither typescript nor runtime errors stop it. It seems to be happening with models that consist only of array and maybe properties.
Here is a snippet to demonstrate the problem:
const Ref = types.model({})
const Foo = types.model({
bars: types.array(Ref),
someReference: types.maybe(types.reference(Ref))
// prim: types.boolean
})
Foo.create({
bars: [],
barrrr: true // Doesn't compile. Good!
})
const barrr1 = {
a: 1,
b: 2
}
// :( Compiles unless I uncomment prim property in Foo model
Foo.create(barrr1)
const barrr2 = {
bars: [],
barrrr: true
}
// :( Compiles but I can live with that
Foo.create(barrr2)
That's mostly due typescript nature of object checking. Random example: http://www.typescriptlang.org/play/?ssl=16&ssc=1&pln=16&pc=9#code/CYUwxgNghgTiAEAzArgOzAFwJYHtVJxwAooAueAb3igH5yBnDGLVAc3gF8BKcgNxyzAA3ACgRAenHwQMGDhgjEhIlTLwARFHUAaeACNyARk5dRIsHkbwM8ALyVq5TTv1HOoi6isYATHYcG8MYcZpLwqDjSsvKKyhimYmERUXIKSsQU3KFSMqmxxL6mQA
What's most bothering me is that one can pass barrr1 and it compiles even though there are no properties in common between the type of the passed argument and type of the expected parameter. This problem doesn't happen in a simple TS example http://www.typescriptlang.org/play/#code/CYUwxgNghgTiAEAzArgOzAFwJYHtVJxwAoAHWKAWwGcAueAb3igH46qMYtUBzeAXwCUdAG44swANwAoKYkJF6AIzoBGQUA
So if we will fix the title of the issue, The problem is with TypeScript weak types check and MST https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html#weak-type-detection
That's not in correct, but leaser DX, for sure. I think there's related issues to that somewhere
Hey @thehappycoder - sorry it's been a while since anyone got back to you here. I'm inclined to agree that this is a bug, or at the very least, that we ought to warn or do something a little noisier when entirely incorrect data is passed in to create.
I know it's been a few years, so if this is no longer relevant to you, I totally understand. But if you're interested in helping out, I'd be happy to do some initial investigation with you.
I'm going to label this as a bug, and we'll see how/where this falls in priorities.
Thanks!