TypeSript: сужение от более широкого типа

#typescript

#typescript

Вопрос:

Как я могу переписать этот код, чтобы избежать ошибки TypeScript:

 const level: "debug" | "info" | "warn" | "error" | "custom" = "custom";

if (level in window.console) {
        // Error: Element implicitly has an 'any' type because expression of type '"custom"' can't be used to index type 'Console'.    
        window.console[level].call(
          window.console,
          `Level is: ${level}`
        );
    } else  {
        window.console.log.call(
          window.console,
          `Level is: ${level}`
        );
    }
 

Спасибо.

Ответ №1:

Используйте защиту типа:

 // alias for convenience
type ConsoleKey = keyof typeof console;

function isConsoleKey(val: string): val is ConsoleKey {
    return val in console;
}

const level: string = "custom";

if (isConsoleKey(level)) {
    // you don't need call since `this` will automatically be set    
    console[level](
        `Level is: ${level}`
    );
} else  {
    console.log(
        `Level is: ${level}`
    );
}