@baukit/type-guards 0.30.6 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,16 +1,42 @@
|
|
|
1
1
|
# `@baukit/type-guards`
|
|
2
2
|
|
|
3
3
|
Runtime type guards for validating `unknown` JSON without double casts. The package has no
|
|
4
|
-
dependencies
|
|
4
|
+
dependencies. The Baukit packages that parse tokens, plans and API payloads share it.
|
|
5
|
+
|
|
6
|
+
## Exports
|
|
7
|
+
|
|
8
|
+
| Guard | Accepts |
|
|
9
|
+
| -------------------------- | ------------------------------------------------- |
|
|
10
|
+
| `isRecord` | any object that is not `null` and not an array |
|
|
11
|
+
| `isString` | any string |
|
|
12
|
+
| `isNonEmptyString` | a string with at least one character |
|
|
13
|
+
| `isBoolean` | `true` or `false` |
|
|
14
|
+
| `isSafeInteger` | a number for which `Number.isSafeInteger` is true |
|
|
15
|
+
| `isNonNegativeSafeInteger` | a safe integer of zero or more |
|
|
16
|
+
| `isStringArray` | an array whose every item is a string |
|
|
17
|
+
| `nullable(guard)` | whatever `guard` accepts, and `null` |
|
|
18
|
+
|
|
19
|
+
Each guard is a TypeScript type predicate, so a passing check narrows the value.
|
|
20
|
+
|
|
21
|
+
## Example
|
|
5
22
|
|
|
6
23
|
```ts
|
|
7
|
-
import { isNonEmptyString, isRecord } from '@baukit/type-guards';
|
|
24
|
+
import { isNonEmptyString, isRecord, isSafeInteger, nullable } from '@baukit/type-guards';
|
|
25
|
+
|
|
26
|
+
interface Claims {
|
|
27
|
+
readonly sub: string;
|
|
28
|
+
readonly exp: number | null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const isOptionalInteger = nullable(isSafeInteger);
|
|
8
32
|
|
|
9
|
-
function
|
|
10
|
-
if (!isRecord(
|
|
11
|
-
|
|
33
|
+
export function parseClaims(value: unknown): Claims | undefined {
|
|
34
|
+
if (!isRecord(value)) return undefined;
|
|
35
|
+
const { sub, exp } = value;
|
|
36
|
+
if (!isNonEmptyString(sub) || !isOptionalInteger(exp)) return undefined;
|
|
37
|
+
return { sub, exp };
|
|
12
38
|
}
|
|
13
39
|
```
|
|
14
40
|
|
|
15
|
-
|
|
16
|
-
|
|
41
|
+
The baukit rules forbid `as unknown as T` on untrusted data. Use these guards instead. See the
|
|
42
|
+
[frontend guide](../../../docs/guide/frontend.md).
|