首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在console.log、console.warn、console.error中重写TypeScript

如何在console.log、console.warn、console.error中重写TypeScript
EN

Stack Overflow用户
提问于 2022-10-22 12:53:26
回答 1查看 52关注 0票数 0

我很接近让它按我想要的方式工作。

请参阅下面的代码及其输出。

代码语言:javascript
运行
复制
import util from 'util';

import chalk from 'chalk'; // https://www.npmjs.com/package/chalk

import { getFormattedUtcDatetimeNow } from './datetime.js';

const success = chalk.bgGreen;

const styles = {
  log: chalk,
  error: chalk.bold.red,
  warn: chalk.hex('#FFA500'), // Orange color
  info: chalk.gray,
  debug: chalk.blue,
};

type Arguments = any;

// TODO: Fix this since it leads to weird displays of square brackets [].
function getArgumentsPreserved(providedArguments: Arguments): string {
  // https://nodejs.org/en/knowledge/getting-started/how-to-use-util-inspect/
  // https://github.com/chalk/chalk/issues/118#issuecomment-1221385194
  return util.inspect(providedArguments, { colors: false, depth: null });
}

for (const style of Object.keys(styles)) {
  const originalStyle = console[style];
  const callback = styles[style];
  console[style] = function (...providedArguments: Arguments) {
    Reflect.apply(originalStyle, this, [getFormattedUtcDatetimeNow(), callback(getArgumentsPreserved(providedArguments))]);
  };
}

运行命令后输出:

代码语言:javascript
运行
复制
const object = { ab: 'cd', one: { two: 3 } };
console.log('demo', object);
2022-10-22 12:45:08 UTC [ 'demo', { ab: 'cd', one: { two: 3 } } ]

如何避免由[添加的额外]util.inspect()

此外,如何添加适当的类型以避免这些TypeScript错误?

代码语言:javascript
运行
复制
    shared/helpers/logging.ts:29:28 - error TS2304: Cannot find name 'originalLog'.

    29 type originalType = typeof originalLog;
                                  ~~~~~~~~~~~
    shared/helpers/logging.ts:32:39 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Console'.
      No index signature with a parameter of type 'string' was found on type 'Console'.

    32   const originalStyle: originalType = console[style];
                                             ~~~~~~~~~~~~~~
    shared/helpers/logging.ts:33:20 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ log: Chalk & ChalkFunction & { supportsColor: false | ColorSupport; Level: Level; Color: Color; ForegroundColor: ForegroundColor; BackgroundColor: BackgroundColor; Modifiers: Modifiers; stderr: Chalk & { ...; }; }; error: Chalk; warn: Chalk; info: Chalk; debug: Chalk; }'.
      No index signature with a parameter of type 'string' was found on type '{ log: Chalk & ChalkFunction & { supportsColor: false | ColorSupport; Level: Level; Color: Color; ForegroundColor: ForegroundColor; BackgroundColor: BackgroundColor; Modifiers: Modifiers; stderr: Chalk & { ...; }; }; error: Chalk; warn: Chalk; info: Chalk; debug: Chalk; }'.

    33   const callback = styles[style];
                          ~~~~~~~~~~~~~
    shared/helpers/logging.ts:34:3 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Console'.
      No index signature with a parameter of type 'string' was found on type 'Console'.

    34   console[style] = function (...providedArguments: Arguments) {

在下面的评论之后更新

代码语言:javascript
运行
复制
for (const style of Object.keys(styles) as Array<keyof Console>) {
  const originalStyle = console[style];
  const callback = styles[style];
  console[style] = function (...providedArguments: Arguments) {
    Reflect.apply(originalStyle, this, [getFormattedUtcDatetimeNow(), callback(getArgumentsPreserved(providedArguments))]);
  };
}

更新#2

EN

回答 1

Stack Overflow用户

发布于 2022-10-22 13:07:14

您的函数应该映射到每个元素上,然后加入结果。您将获得额外的[],因为您正在检查数组,即参数。

代码语言:javascript
运行
复制
type Arguments = any[]; // needs to be an array to use `map`

function getArgumentsPreserved(providedArguments: Arguments): string {
  return providedArguments.map((a) => util.inspect(a, { colors: false, depth: null })).join(" ");
}

在循环中,可以将Object.keys(styles)转换为styles的键。

代码语言:javascript
运行
复制
for (const style of Object.keys(styles) as Array<keyof typeof styles>) {
  const originalStyle = console[style];
  const callback = styles[style];
  console[style] = function (...providedArguments: Arguments) {
    Reflect.apply(originalStyle, this, [getFormattedUtcDatetimeNow(), callback(getArgumentsPreserved(providedArguments))]);
  } as any;
}

然后,当尝试使用键console索引到style时,不应该出现错误。不幸的是,我认为在重新分配该方法时修复错误的最简单方法是将其转换为any。在这里,它没有害处(也不会传播),所以使用any是很好的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74163732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档