Reputation: 67
How can I rewrite this code to avoid TypeScript error:
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}`
);
}
Thanks.
Upvotes: 0
Views: 62
Reputation: 35560
Use a type guard:
// 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}`
);
}
Upvotes: 1