From 8562af6901d1b32d230a540b549661a2b9bb5f18 Mon Sep 17 00:00:00 2001 From: Endel Dreyer Date: Sun, 23 Jul 2023 10:15:06 -0300 Subject: [PATCH] ArraySchema: ignore, warn, and do not throw when pushing undefined value. --- src/types/ArraySchema.ts | 5 +++++ test/ArraySchemaTest.ts | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) 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); });