#Dynamic Typing

15 messages · Page 1 of 1 (latest)

gilded robin
#

Why is in case "ERROR" the variable "error" not strictly typed as "Error" and still either "string" or "Error"?

type Levels = {
    ERROR: [error: Error];
    WARNING: [message: string];
    INFO: [message: string];
};

public log<K extends keyof Levels>(level: K, ...args: Levels[K]): void {
    const date = new Date();

    let message: string | null = null;

    switch (level) {
        case "ERROR": {
            const error = args[0];
            message = `[${Moment(date).format("YYYY-MM-DD HH:mm:ss")}] [${level}] - ${error.message}\n\n`;
        }
    }
}
glacial bison
#

because narrowing level doesn't narrow args

#

those are 2 different objects

#

even tho they are linked, TS can't really understand it

#

you could cast error as Error

#

or simply refractor the code to avoid the problem entierly (the code isn't ideal imho)

gilded robin
glacial bison
#

making different methods, one per level

gilded robin
#

Okay, let me do that.

gilded robin
# glacial bison making different methods, one per level

Like that? ```ts
public log(level: "ERROR", content: Error): void;
public log(level: "WARNING", content: string): void;
public log(level: "INFO", content: string): void;
public log(level: "ERROR" | "WARNING" | "INFO", content: Error | string): void

glacial bison
#

that's overload

#

it would also work

gilded robin
#

Ah, now I know what you mean.

gilded robin
glacial bison
#

I was mainly talking about

public log() {}
public warn() {}
public error() {}