From 843c213c07ff819f2619407514691e7edde2b5fc Mon Sep 17 00:00:00 2001 From: Nikita Galaiko Date: Tue, 7 Feb 2023 09:14:12 +0100 Subject: [PATCH] example of type guards --- src/lib/crdt.ts | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/lib/crdt.ts b/src/lib/crdt.ts index 814d100c0..220974984 100644 --- a/src/lib/crdt.ts +++ b/src/lib/crdt.ts @@ -1,10 +1,22 @@ import { Doc } from "yjs"; import { diffChars } from "diff"; -export type Delta = - | { retain: number } - | { delete: number } - | { insert: string }; +type DeltaRetain = { retain: number }; +type DeltaDelete = { delete: number }; +type DeltaInsert = { insert: string }; + +export type Delta = DeltaRetain | DeltaDelete | DeltaInsert; + +export namespace Delta { + export const isRetain = (delta: Delta): delta is DeltaRetain => + "retain" in delta; + + export const isDelete = (delta: Delta): delta is DeltaDelete => + "delete" in delta; + + export const isInsert = (delta: Delta): delta is DeltaInsert => + "insert" in delta; +} // Compute the set of Yjs delta operations (that is, `insert` and // `delete`) required to go from initialText to finalText.