From 406c08f26d6012f55c575d00094b4d40a8931bf4 Mon Sep 17 00:00:00 2001 From: Benedikt Franke Date: Mon, 22 Apr 2024 09:43:20 +0200 Subject: [PATCH] feat: add isNonEmptyString --- package.json | 2 +- src/typeGuards.test.ts | 18 +++++++++++++++++- src/typeGuards.ts | 9 +++++---- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 48e8dcf..cf99012 100644 --- a/package.json +++ b/package.json @@ -79,5 +79,5 @@ "ts-node": "^9.1.1", "typescript": "^5.3.3" }, - "packageManager": "yarn@4.1.0" + "packageManager": "yarn@4.1.1" } diff --git a/src/typeGuards.test.ts b/src/typeGuards.test.ts index dc14d1f..7ddaec3 100644 --- a/src/typeGuards.test.ts +++ b/src/typeGuards.test.ts @@ -1,7 +1,23 @@ import { assertFalse, assertTrue } from './predicates.test'; -import { isArrayOfStrings, isEmptyObject, isNotNullish } from './typeGuards'; +import { + isArrayOfStrings, + isEmptyObject, + isNonEmptyString, + isNotNullish, + isString, +} from './typeGuards'; describe('typeGuards', () => { + describe('isString', () => { + assertTrue(isString, ['foo', '1', 'true', '']); + assertFalse(isString, [/foo/, 1, true, null, undefined]); + }); + + describe('isNonEmptyString', () => { + assertTrue(isNonEmptyString, ['foo', '1', 'true']); + assertFalse(isNonEmptyString, ['', /foo/, 1, true, null, undefined]); + }); + describe('isNotNullish', () => { assertTrue(isNotNullish, ['', [], {}, false]); assertFalse(isNotNullish, [null, undefined]); diff --git a/src/typeGuards.ts b/src/typeGuards.ts index 59155f1..9432c3a 100644 --- a/src/typeGuards.ts +++ b/src/typeGuards.ts @@ -2,15 +2,16 @@ export function isString(value: unknown): value is string { return typeof value === 'string'; } +export function isNonEmptyString(value: unknown): value is Exclude { + return isString(value) && value !== ''; +} + export function isNotNullish(value: T): value is NonNullable { return value != null; } export function isArrayOfStrings(value: unknown): value is Array { - return ( - value instanceof Array && - value.every((record) => typeof record === 'string') - ); + return value instanceof Array && value.every(isString); } export function isEmptyObject(value: unknown): value is Record {