mobxjs / mobx-state-tree

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

Additional `undefined` case inside `union` type #1929

Open iy-work opened 2 years ago

iy-work commented 2 years ago

Question

Why is the instance type for types.union(types.string, types.array(types.number)) inferred as string | (number[] & ...) | undefined? I thought that it should be just string | (number[] & ...) without undefined case. Is this behaviour intended or it is a mistake in typings?

playground link

coolsoftwaretyler commented 1 year ago

Hey @iy-work - sorry it took so long to get back to you!

From my interpretation of the union docs, I think this typing is probably for the case mentioned:

If the correct type cannot be inferred unambiguously from a snapshot, provide a dispatcher function to determine the type

It seems possible that the TypeScript typings for types.union have to account for scenarios where a type cannot be inferred, and a dispatcher function isn't provided (or the function returns undefined).

Another thing that leads me to believe it is that the determineType method declares a return type of possible undefined.

Is that a satisfactory answer for you? Happy to dig in a lil more! If I don't hear back in a week or two, I will probably close out this issue.