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?

3
  • 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 (<Child>d); } Where Child and Parent is custom types Commented Mar 28, 2018 at 11:12
  • Maybe this will be useful: stackoverflow.com/a/40718205/9050727 Commented Mar 28, 2018 at 11:12
  • Or this: aliolicode.com/2016/04/23/type-checking-typescript Commented Mar 28, 2018 at 11:15

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Is there any better way of doing this, as I have many properties?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.