Giora Guttsait
Giora Guttsait

Reputation: 1300

How do define this model in typescript

I have a json model that looks like this

{
    "loggers" : {
        "logger1" : {
            "name" : "logger1",
            "level" : "DEBUG",
            "sub_loggers" :{
                "logger1.nested_logger1" : {
                    "name": "logger1.nested_logger1",
                    "level": "INFO"
                },
                "logger1.nested_logger2" : {
                    "name": "logger1.nested_logger2",
                    "level": "INFO",
                    "sub_loggers": {
                        "logger1.nested_logger2.more_of_that" : {
                            "name": "logger1.nested_logger2.more_of_that",
                            "level": "INFO"
                        }
                    }
                }
            }
        },
        "logger2" : {
            "name": "logger2",
            "level": "WARN"
        }
    }
}

I want to save the model as I receive it from a HTTP request in a variable, but I want it to be mapped, so I don't have to use any.

If there's a way to separate it into 2 models, I'd want that even more, I just don't know how to map it because sub_loggers is not an array, it's an object who's key names are also the names of the loggers they represent.

Upvotes: 1

Views: 371

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164297

Here's one option:

type Level = "DEBUG" | "INFO" | "WARN" | "ERROR";

type Loggers = {
    [name: string]: Logger;
}

interface Logger {
    name: string;
    level: Level;
    sub_loggers?: Loggers;
}

let json = YOUR_JSON as { loggers: Loggers };
let loggers: Loggers = json["loggers"];

(code in playground)


Edit

To answer your comment questions:

  1. Yes, ? marks an optional property.
  2. I haven't used classes at all, I used interfaces and type aliases.
    The differences between interfaces and type aliases is explained in the linked documentation.
    I haven't used classes because from your question it seemed that you're looking only to represent your json structure so that the compiler will use type safety.
    If you need to have actual instances so that you'll have functionality (methods) and not just having data objects, then you'll need to use classes.

Upvotes: 2

Related Questions