From 4e37c4b75a2a0646a420201ef0c8197b6822ca07 Mon Sep 17 00:00:00 2001 From: akolarski <37934108+akolarski@users.noreply.github.com> Date: Sun, 24 Jul 2022 22:49:54 +0300 Subject: [PATCH 1/2] Make parser check optional fields too. When creating a Type Guard pass interface with all required fields to the parser but parser still returns the original interface. --- src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 8f9f9a6..2666971 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,7 +5,7 @@ function hasProperties(obj: T, ...keys: K[]) } -const createTypeGuard = (parse: Parser) => (value: unknown): value is T => { +const createTypeGuard = (parse: Parser>) => (value: unknown): value is T => { return parse(value) !== null; }; From e02a62912337cd055cb64d2781084e5cddce1a14 Mon Sep 17 00:00:00 2001 From: akolarski <37934108+akolarski@users.noreply.github.com> Date: Sun, 24 Jul 2022 23:14:55 +0300 Subject: [PATCH 2/2] A better approach is for the parser to require for the whole to be defined. --- src/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/index.ts b/src/index.ts index 2666971..49710cf 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,11 +1,11 @@ -type Parser = (value: unknown) => T | null; +type Parser = (value: unknown) => Required | null; function hasProperties(obj: T, ...keys: K[]): obj is T & { [J in K]: unknown } { return !!obj && keys.every(key => obj.hasOwnProperty(key)); } -const createTypeGuard = (parse: Parser>) => (value: unknown): value is T => { +const createTypeGuard = (parse: Parser) => (value: unknown): value is T => { return parse(value) !== null; };