Typescript TypeSript:从较宽的类型缩小
如何重写此代码以避免TypeScript错误:Typescript 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
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}`
);
}
谢谢。使用:
// 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}`
);
}