Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions src/utils/cast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ const isBooleanString = (value: string): value is 'true' | 'false' => {
return value === 'true' || value === 'false';
};

const isNullString = (value: string): value is 'null' => {
return value === 'null';
const isNull = (value: string | null): value is 'null' | null => {
return value === 'null' || value === null;
};

const isJsonStructure = (value: string): boolean => {
Expand Down Expand Up @@ -43,8 +43,8 @@ const parseBoolean = (value: string): boolean | string => {
return value;
};

const parseNull = (value: string): null | string => {
return value === 'null' ? null : value;
const parseNull = (value: string | null): null | string => {
return isNull(value) ? null : value;
};

const parseJson = (value: string): unknown => {
Expand All @@ -66,7 +66,7 @@ const parseAuto = (value: string): unknown => {
return value === 'true';
}

if (isNullString(value)) {
if (isNull(value)) {
return null;
}

Expand All @@ -85,7 +85,11 @@ const parseAuto = (value: string): unknown => {
return value;
};

export const cast = (value: string, type: CastType = 'auto'): unknown => {
export const cast = (value: string | null, type: CastType = 'auto'): unknown => {
if (value === null) {
return null;
}

switch (type) {
case 'string':
return value;
Expand Down
12 changes: 12 additions & 0 deletions test/specs/utils/cast.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ describe('cast', () => {
expect(cast('null')).toBeNull();
});

it('casts null value', () => {
expect(cast(null as unknown as string)).toBeNull();
});

it('casts integer strings', () => {
expect(cast('0')).toBe(0);
expect(cast('1')).toBe(1);
Expand Down Expand Up @@ -62,6 +66,14 @@ describe('cast', () => {
expect(cast('01', 'string')).toBe('01');
});

it('keeps null value as null for any rule', () => {
expect(cast(null, 'string')).toBeNull();
expect(cast(null, 'number')).toBeNull();
expect(cast(null, 'boolean')).toBeNull();
expect(cast(null, 'null')).toBeNull();
expect(cast(null, 'json')).toBeNull();
});

it('casts value to number for number rule when possible', () => {
expect(cast('11', 'number')).toBe(11);
expect(cast('1.5', 'number')).toBe(1.5);
Expand Down
Loading