Description
Bug report
- I've checked documentation and searched for existing issues
- I've made sure my project is based on the latest MST version
- Fork this code sandbox or another minimal reproduction.
Sandbox link or minimal reproduction code
type TodoType = "task" | "bug";
// written as a separate variable for other references that are not tied to MST
const todoTypes: ReadonlyArray<TodoType> = ["task", "bug"];
const todoTypes: ["task", "bug"] as const // same as above, but shorter, for TS >= 3.4
export const Todo = types
.model("Todo", {
id: types.optional(types.number, () => Math.random()),
title: types.string,
finished: false,
type: types.enumeration(todoTypes) // error
})
Describe the expected behavior
The above code should compile
Describe the observed behavior
Line 10 shows the following error:
Argument of type 'ReadonlyArray' is not assignable to parameter of type 'TodoType[]'.
Type 'ReadonlyArray' is missing the following properties from type 'TodoType[]': pop, push, reverse, shift, and 6 more
This is due to enumeration
accepting T[], and not a ReadonlyArray<T>
/readonly T[]
(latter as of TS 3.4).
This behavior is not just for this case, but also in other places in MST (e.g. types.union
.
My suggestion is to accept the minimal necessary interface for arrays when possible. This should cover most, if not all cases, since they are usually not directly used anyway, at least for types. This is more important with TypeScript 3.4+ since it's now much less of a hassle to make an array a ReadonlyArray
, especially with as const
, but also with the readonly
modifier added to more use-uses (e.g. function parameters).
If this is handled, upgrading to TypeScript 3.4 (or greater) should be considered, since it makes the changes easier to type. e.g.:
// TS 3.3
export function enumeration<T extends string>(options: ReadonlyArray<T>): ISimpleType<UnionStringArray<T[]>>
export function enumeration<T extends string>(
name: string,
options: ReadonlyArray<T>
): ISimpleType<UnionStringArray<T[]>>
// TS 3.4
export function enumeration<T extends string>(options: readonly T[]): ISimpleType<UnionStringArray<T[]>>
export function enumeration<T extends string>(
name: string,
options: readonly T[]
): ISimpleType<UnionStringArray<T[]>>
At the cost of supporting only TS 3.4+ (maybe we can transpile these to ReadonlyArray
in the output type declarations?)