diff --git a/src/types/ArraySchema.ts b/src/types/ArraySchema.ts index 4b486166..b8dc99d7 100644 --- a/src/types/ArraySchema.ts +++ b/src/types/ArraySchema.ts @@ -162,6 +162,11 @@ export class ArraySchema implements Array, SchemaDecoderCallbacks { } setAt(index: number, value: V) { + if (value === undefined || value === null) { + console.error("ArraySchema items cannot be null nor undefined; Use `deleteAt(index)` instead."); + return; + } + if (value['$changes'] !== undefined) { (value['$changes'] as ChangeTree).setParent(this, this.$changes.root, index); } diff --git a/test/ArraySchemaTest.ts b/test/ArraySchemaTest.ts index 0ba038d2..4abecc0a 100644 --- a/test/ArraySchemaTest.ts +++ b/test/ArraySchemaTest.ts @@ -5,7 +5,7 @@ import { State, Player } from "./Schema"; import { ArraySchema, Schema, type, Reflection, filter, MapSchema, dumpChanges, filterChildren } from "../src"; describe("ArraySchema Tests", () => { - xit("should allow to setAt an undefined value", () => { + it("should not crash when pushing an undefined value", () => { class Block extends Schema { @type("number") num: number; } @@ -18,7 +18,7 @@ describe("ArraySchema Tests", () => { const decodedState = new State(); decodedState.decode(state.encode()); - assert.strictEqual(decodedState.blocks.length, 2); + assert.strictEqual(decodedState.blocks.length, 1); assert.ok(decodedState.blocks.at(0) instanceof Block); assert.ok(decodedState.blocks.at(1) === undefined); });