1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Is there a way in TypeScript to do custom JSON deserialization within a class?

Discussão em 'Angular' iniciado por Kayden Miller, Junho 12, 2025.

  1. The Goal


    I am working on a project where we have id's comming back from the server in a format that is a prefix followed by a guid (prefix_{guid}). This is so that we know what the specific ID type is rather than just having a bunch of guids flying around that we don't know what they mean other than by reading a bunch of code (basically context clues). What I would like to do is have the value example_9B75ECBC-5DA8-4821-B9DF-2EF5DE9597F5 be converted into a value object class where it can be validated.

    Yes, I'm aware I could just use a string and then I wouldn't need to do this at all. That is not the point of this exercise though, the point is to NOT use a string as a string would match any string and not just this specific type of string. This also relates to a topic called primative obsession which I'm doing some research on for this as well.

    Example class

    export class ExampleId {
    private _value: string;

    constructor(value: string) {
    if (!this.isValid(value)) {
    throw new Error(`Invalid project status id '${value}'`);
    }

    this._value = value;
    }

    public get value(): string {
    return this._value;
    }

    private isValid(value: string): boolean {
    return /^example_[0-9A-Fa-f]{8}-?[0-9A-Fa-f]{4}-?4[0-9A-Fa-f]{3}-?[89ABab][0-9A-Fa-f]{3}-?[0-9A-Fa-f]{12}$/.test(value);
    }

    /**
    * This is used by JSON.stringify() to convert to an the expected value that the server wants
    * THIS DOES WORK AS EXPECTED
    **/
    private toJSON() {
    return this.value;
    }

    /**
    * THIS DOES NOT
    **/
    private fromJSON(input: string): ExampleId {
    return new ExampleId(input);
    }
    }



    I want to be able to throw an error when/if I ever get an ID value that isn't this specific type of ID, so that I can pass around this type and know that it will always be the correct underlying value format.

    This should mean that when I have a class of:

    export class ExampleResponse {
    constructor(
    public id: ExampleId,
    public otherData: any) {
    }
    }


    This would ideally serialize into the respective types but also be able to deserialize into the expected json which doesn't follow the pattern of the object itself directly.

    I've been looking around for a bit and I've found the toJSON method that you can monkey patch to customize the serialization process but I haven't found an equivalent for deserialization.

    The closest I've seen so far was potentially providing a fn to the reviver part of JSON.parse() but that feels clucky and really wouldn't work either way for my situation as I'm in angular and would like to be able to do this with the HttpClient if possible.

    The Question


    Does anyone know of a way to handle custom deserialization at the class level (or other levels, but ideally class) in TypeScript? Preferably, this should work for any TS project, but Angular-specific will still work, but may not work for as many other people.

    Continue reading...

Compartilhe esta Página