Javascript 扩展TypeScript的控制台接口

Javascript 扩展TypeScript的控制台接口,javascript,typescript,react-native,Javascript,Typescript,React Native,我想在window.console全局中添加一个对象 import Reactotron from 'reactotron-react-native'; window.console.tron = Reactotron; 尽管我这样做时,TypeScript会抱怨新对象: 错误TS2339:类型“Console”上不存在属性“tron” 我正在考虑扩展控制台界面: interface ConsoleWithTron extends Console { tron: any }; 尽管如此

我想在window.console全局中添加一个对象

import Reactotron from 'reactotron-react-native';

window.console.tron = Reactotron;
尽管我这样做时,TypeScript会抱怨新对象:

错误TS2339:类型“Console”上不存在属性“tron”

我正在考虑扩展控制台界面:

interface ConsoleWithTron extends Console {
  tron: any
};
尽管如此,我不知道如何将这个新接口分配给我的全局控制台对象

帮帮忙太好了


谢谢。

您只需扩充
控制台
界面本身即可。见:

如果要从模块内部扩充
控制台
,必须将其包装在
声明全局{}
块中。看


更妙的是,我们可以在前面的答案中添加带有linting的类型安全性

/* eslint-disable import/no-extraneous-dependencies */
import { Reactotron } from 'reactotron-core-client';
import { ReactotronReactNative } from 'reactotron-react-native';

declare global {
  interface Console {
    tron: Reactotron<ReactotronReactNative> & ReactotronReactNative;
  }
}

为什么控制台是大写的?@evolutionxbox,因为它指的是我们的界面控制台,最初来自
node\u modules/@types/node/globals.d.ts
,但当从我们的全局
窗口
变量作为属性调用时,它采用了camelCase形式。@Leo三年@进化Xbox哈哈为necro道歉!❤️执行此操作后,我仍然从tsc收到相同的错误。。。。在将
tron
添加到console对象之前,我已经定义了接口。是否在模块中添加此接口?您可能需要将其包装在
声明全局{}
中。看见
declare global {
    interface Console {
        tron: any
    }
}
/* eslint-disable import/no-extraneous-dependencies */
import { Reactotron } from 'reactotron-core-client';
import { ReactotronReactNative } from 'reactotron-react-native';

declare global {
  interface Console {
    tron: Reactotron<ReactotronReactNative> & ReactotronReactNative;
  }
}
console.tron = Reactotron;