Type safety

at runtime

with json decoders

typescript

is not perfect

what's the problem?

underneath, typescript is just

plain javascript

No interfaces

and type aliases

No runtime validation

after transpilation

what's

the solution?

json decoders

elm

ts.data.json

what about            ?

Runtype

io-ts

etc...

JsonDecoder.string: Decoder<string>;
JsonDecoder.number: Decoder<number>;
JsonDecoder.boolean: Decoder<boolean>;

basic decoders

import { JsonDecoder } from 'ts.data.json';

interface Person {
  name: string;
}

const personDecoder = JsonDecoder.object<Person>(
  { name: JsonDecoder.string },
  'Person'
);

const invalidPerson = { name: 1 };

personDecoder
  .decodePromise(invalidPerson)
  .then(console.log)
  .catch(console.error);

// <Person> decoder failed at key "name" 
// with error: 1 is not a valid string

your turn!

TRY THEM OUT!

KAJETAN ŚWIĄTEK
kajetansw
dev-self-start
Made with Slides.com