mobx-state-tree icon indicating copy to clipboard operation
mobx-state-tree copied to clipboard

Typesafety loophole: can pass garbage to SomeModel.create

Open thehappycoder opened this issue 5 years ago • 4 comments

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)

thehappycoder avatar Jan 24 '20 22:01 thehappycoder

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

Bnaya avatar Feb 03 '20 13:02 Bnaya

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

thehappycoder avatar Feb 03 '20 21:02 thehappycoder

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

Bnaya avatar Feb 04 '20 07:02 Bnaya

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!

coolsoftwaretyler avatar Jun 30 '23 21:06 coolsoftwaretyler