Safer JSON.parse()
validating by TypeScript types
Write a format of JSON once, Derive the type automatically at compile-time.
npm install -S git+https://github.com/nwtgck/ts-json-validator#v0.1.2
import {nul, bool, num, str, literal, opt, arr, tuple, obj, union, TsType, validatingParse} from 'ts-json-validator';
// Create a format
const personFormat = obj({
name: str,
age: num
});
// Generate Person type
// IMPORTANT: Type is derived at compile-time. Just a write format once!
type Person = TsType<typeof personFormat>;
// Safer parse than JSON.parse()
const p1: Person | undefined = validatingParse(personFormat, '{"name": "jack", "age": 8}');
const myObj: {[key: string]: any} = {name: "jack", age: 8};
const p2: Person | undefined = validate(personFormat, myObj);
// => not undefined
const myObj2: any = {name: "jack", age: "this is a text"};
isValid(personFormat.runtimeType, myObj2);
// => false (because type of age should be number)
The main feature is that type Person
is automatically derived. So you just define the format/structure object of JSON such as personFormat
. Then you can get a type
for free.
import {nul, bool, num, str, literal, opt, arr, tuple, obj, union, TsType, validatingParse} from 'ts-json-validator';
// Create a format
const myObj1Format = obj({
// String array - string[]
myStrs: arr(str),
// Nested object - (myFlag: boolean)
myObj: obj({
myFlag: bool
}),
// Union Type - string | number | bool
strOrNumOrBool: union(str, num, bool),
// Object array - {prop1: number, prop2: string}[]
myObjs: arr(obj({
prop1: num,
prop2: str
})),
// Optional property(myOptional?: number)
myOptional: opt(num),
// Literal Type - (myLiteral: 'MY_LITERAL')
myLiteral: literal('MY_LITERAL' as const),
// Literal Union Type - ('red' | 'blue')
myLitUnion: union(literal('red' as const), literal('blue' as const)),
// Nullable - (string | null)
myNullable: union(str, nul),
// Tuple - [string, boolean, number]
myTuple: tuple(str, bool, num),
});
// Generate MyObj1 type
// IMPORTANT: Type is derived at compile-time. Just write a format once!
type MyObj1 = TsType<typeof myObj1Format>;
In Union Type, T1 | T2 | ... | T64
is supported. In tuple, [T1, T2, ..., T64]
is supported.
You can find errors at compile-time, not runtime!
myStrs
should be an string array, but 128
is included.
myStrs
is required, but missing.
myLiteral
should be 'MY_LITERAL'
type, but found 'YOUR LITERAL'