Skip to content

Commit 332d655

Browse files
authored
fix: preserve null values in cast (#99)
1 parent 1cd19bc commit 332d655

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

src/utils/cast.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ const isBooleanString = (value: string): value is 'true' | 'false' => {
22
return value === 'true' || value === 'false';
33
};
44

5-
const isNullString = (value: string): value is 'null' => {
6-
return value === 'null';
5+
const isNull = (value: string | null): value is 'null' | null => {
6+
return value === 'null' || value === null;
77
};
88

99
const isJsonStructure = (value: string): boolean => {
@@ -43,8 +43,8 @@ const parseBoolean = (value: string): boolean | string => {
4343
return value;
4444
};
4545

46-
const parseNull = (value: string): null | string => {
47-
return value === 'null' ? null : value;
46+
const parseNull = (value: string | null): null | string => {
47+
return isNull(value) ? null : value;
4848
};
4949

5050
const parseJson = (value: string): unknown => {
@@ -66,7 +66,7 @@ const parseAuto = (value: string): unknown => {
6666
return value === 'true';
6767
}
6868

69-
if (isNullString(value)) {
69+
if (isNull(value)) {
7070
return null;
7171
}
7272

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

88-
export const cast = (value: string, type: CastType = 'auto'): unknown => {
88+
export const cast = (value: string | null, type: CastType = 'auto'): unknown => {
89+
if (value === null) {
90+
return null;
91+
}
92+
8993
switch (type) {
9094
case 'string':
9195
return value;

test/specs/utils/cast.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ describe('cast', () => {
1212
expect(cast('null')).toBeNull();
1313
});
1414

15+
it('casts null value', () => {
16+
expect(cast(null as unknown as string)).toBeNull();
17+
});
18+
1519
it('casts integer strings', () => {
1620
expect(cast('0')).toBe(0);
1721
expect(cast('1')).toBe(1);
@@ -62,6 +66,14 @@ describe('cast', () => {
6266
expect(cast('01', 'string')).toBe('01');
6367
});
6468

69+
it('keeps null value as null for any rule', () => {
70+
expect(cast(null, 'string')).toBeNull();
71+
expect(cast(null, 'number')).toBeNull();
72+
expect(cast(null, 'boolean')).toBeNull();
73+
expect(cast(null, 'null')).toBeNull();
74+
expect(cast(null, 'json')).toBeNull();
75+
});
76+
6577
it('casts value to number for number rule when possible', () => {
6678
expect(cast('11', 'number')).toBe(11);
6779
expect(cast('1.5', 'number')).toBe(1.5);

0 commit comments

Comments
 (0)