2
class Book {
    title: string;
    datePublished: Date;

    static unserialize(str) {
        let ret = JSON.parse(str, (key, value) => {
            switch (key) {

                case 'datePublished': return new Date(value);

                default:return value;
            }
        }) as Book;

        return ret;
    }
}

When unseralizing an object you can use the revive function in JSON.parse like in the sample. But you are accessing the properties of the object by name in constant string thus losing the "control" of typescript (for example refactoring changing the name of a prop would not be reflected in the switch cases).

Is there any better way to use typescript's possibilities?

tru7
  • 6,348
  • 5
  • 35
  • 59
  • You can create custom model according you incomeJSON format and then to use `instanceof` or use this conctruction: `function isJsonNode(d: Parent | Child): pet is Child { return (d); }` Where `Child` and `Parent` is custom types – Jessie Mar 28 '18 at 11:12
  • Maybe this will be useful: https://stackoverflow.com/a/40718205/9050727 – Jessie Mar 28 '18 at 11:12
  • Or this: https://aliolicode.com/2016/04/23/type-checking-typescript/ – Jessie Mar 28 '18 at 11:15

1 Answers1

1

Not sure if it's the best solution but I've come across a way that at least flags mistakes. Refactoring does not change the literal name but it gets flagged with an error after the change.

The trick is setting the type of key as keyof Book

class Book {
    title: string;
    datePublished: Date;

    static unserialize(str) {
        let ret = JSON.parse(str, (key: keyof Book, value) => {  // "keyof Book" does the trick

            switch (key) {

                case 'datePublished': return new Date(value);
                case 'xitle' : return value;        // [ts] Type '"xitle"' is not comparable to type '"title" | "datePublished"
                default:return value;
            }
        }) as Book;

        return ret;
    }
}
tru7
  • 6,348
  • 5
  • 35
  • 59