Gathering detailed insights and metrics for typed-decoders
Gathering detailed insights and metrics for typed-decoders
Gathering detailed insights and metrics for typed-decoders
Gathering detailed insights and metrics for typed-decoders
npm install typed-decoders
Typescript
Module System
Node Version
NPM Version
72.4
Supply Chain
98.9
Quality
76
Maintenance
100
Vulnerability
100
License
TypeScript (100%)
Total Downloads
130,388
Last Day
1
Last Week
19
Last Month
97
Last Year
1,536
4 Stars
102 Commits
2 Forks
2 Watching
1 Branches
3 Contributors
Latest Version
3.4.6
Package Id
typed-decoders@3.4.6
Unpacked Size
29.14 kB
Size
8.16 kB
File Count
21
NPM Version
8.1.2
Node Version
16.13.2
Cumulative downloads
Total Downloads
Last day
-85.7%
1
Compared to previous day
Last week
-44.1%
19
Compared to previous week
Last month
-28.7%
97
Compared to previous month
Last year
-94.8%
1,536
Compared to previous year
4
This module allows you to check if an unknown javascript value conforms to a value of a known type.
npm i --save typed-decoders
You might receive a javascript object from a server that represents a library resource:
1import { Decoders as D, runDecoder, isSuccess, GetType } from './index';
2
3const PersonDecoder = D.obj({
4 id: D.Num,
5 firstName: D.Str,
6 lastName: D.Str,
7 dateOfBirth: D.StrDate
8})
9
10const ResourceDecoder = D.obj({
11 id: D.Num,
12 type: D.Some(D.Lit("book"), D.Lit("blueray"), D.Lit("dvd")),
13 name: D.Str,
14 reservedBy: PersonDecoder
15})
With ResourceDecoder you can assure that an object received from the server is valid.
1const result = runDecoder(ResourceDecoder, valueFromServer);
2if (isSuccess(result)) {
3 // value was decoded succesfully (result.value has the actual value)
4}
The type can be inferred directly from the decoders:
1type Resource = GetType<typeof ResourceDecoder>
The inferred type for Resource is:
1type Resource = { 2 id: number; 3 type: "book" | "blueray" | "dvd"; 4 name: string; 5 reservedBy: { 6 id: number; 7 firstName: string; 8 lastName: string; 9 dateOfBirth: Date; 10 } 11}
This is very useful, because you don't have to write the types manually.
You can easily form different kind of types. For example a tagged unions:
1const SuccessD = D.Obj({ 2 kind: D.Lit("success"), 3 value: D.Num 4}); 5 6const FailureD = D.Obj({ 7 kind: D.Lit("failure"), 8 error: D.Str 9}) 10 11const ResultD = D.Some(SuccessD, FailureD); 12 13type Result = GetType<typeof ResultD>;
The inferred type for Result is:
1type Result = { 2 kind: "success"; 3 value: number; 4} | { 5 kind: "failure"; 6 error: string; 7}
Fail
Accepts never (always fails).Succeed
Accepts always and returns a fixed value.Lit
Accepts literal valueStr
Accepts stringBool
Accepts boolean valueNum
Accepts number valueInt
Accepts a number that is an integerStrNum
Accepts a string that can be converted to numberUndef
Accepts undefined valueDate
Accepts Date instance valueStrDate
Accepts a string that can be converted to a DateNull
Accepts null valuePass
Accepts anything, but decode result type is still unknownOpt
Converts decoder to accept also undefined/null values. Both are converted to undefined.Obj
Create a decoder that accepts an object. Each field is given an own decoder. If two objects are given,
the second specifies optional fields.Rec
Create a decoder that accepts a record (an object with string keys and all field values of same type)Arr
Creates a decoder that accepts an Array. Each item of an array is decoded with same decoderArrT
Creates a transformer from A[] to B[]Some
Creates a decoder that accepts multiple different decodings.Map
Creates a decoder that accepts multiple types, but converts them all to a single type.Def
Converts a decoder to a decoder with a default value.Pipe
Creates a decoder that runs multiple decoders, passing the result to the next decoder. The processing is
stopped at first error.Tuple
Creates a tuple decoder ([S1, S2, ..., Sn ] -> [T1, T2, ..., Tn])TupleN
Creates a tuple decoder with N unknowns (unknown -> [unknown, unknown, ... ])An array of key-value pairs
1const KeyValuesDecoder = D.Arr(D.Obj({ 2 key: D.Str, 3 value: D.Num 4}))
With select you can make multiple type decoders to converge to one type of decoder.
For example to convert numbers, strings, booleans to strings use the following:
1const MySelectDecoder = D.Select( 2 [D.Num, (v: number) => `number ${v}`], 3 [D.Str, (v: string) => `string ${v}`], 4 [D.Bool, (v: boolean) => `boolean ${v}`], 5); 6type MySelect = GetType<typeof MySelectDecoder>
MySelectDecoder
will fail if you give it a value of some other type than the three mentioned above.
If you want to make it to accept all types, you could for example add the following as the last parameter [D.Pass, (v: unknown) =>`unknown \${v}`]
With Map you can combine one or more decoders to return another type of decoder.
Fo example if you have couple of decoders and you would like to combine them to a cleaner structure:
1const CarDecoder = D.Obj({ 2 _brand: D.Some(D.Lit("bmw"), D.Lit("toyota"), D.Lit("volvo")), 3 _model: D.Str 4}) 5 6const PricedDecoder = D.Obj({ 7 _price: D.Num 8}) 9 10const MyCarDecoder = D.Map((c, p) => ({ 11 brand: c._brand, 12 model: c._model, 13 price: p._price 14}), CarDecoder, PricedDecoder) 15 16type MyCar = GetType<typeof MyCarDecoder>;
The inferred type for MyCar is
1type MyCar = { 2 brand: "bmw" | "toyota" | "volvo"; 3 model: string; 4 price: number; 5}
When you have a decoder, you can run it with runDecoder
-function.
1function runDecoder<S, T>(decoder: Transform<T>, value: unknown): Result<T>;
It just calls the decoder (which is a function).
isSuccess
and isFailure
function can be used to check the returned Result
, and also as
type guards to narrow its type:
1const result = runDecoder(myDecoder, value) 2if (isFailure(result)) { 3 // On failure, path and error are available 4 console.log(`decode failed at ${result.path}: ${result.error}`) 5} else { 6 // On success, value contains the decode result 7 console.log('decoded value:', result.value) 8}
If you prefer exceptions instead of returning a success/failure (Result), you can use runDecoderE
.
It will throw an error if the value isn't of correct type.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
Found 3/25 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-12-23
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More