简体   繁体   中英

Extends Console Interface for TypeScript

I would like to add an object in the window.console global.

import Reactotron from 'reactotron-react-native';

window.console.tron = Reactotron;

Although when I do that, TypeScript complains about the new object:

error TS2339: Property 'tron' does not exist on type 'Console'.

I was thinking to extends the Console interface:

interface ConsoleWithTron extends Console {
  tron: any
};

Although, I'm not sure how to assign this new interface to my global console object?

Help would be great!

Thanks.

You can just augment the Console interface itself. See merging interfaces :

interface Console {
    tron: any
}

If you want to augment Console from inside a module, you have to wrap it inside declare global { } block. See global augmentation

declare global {
    interface Console {
        tron: any
    }
}

Even better, we could add type safety with linting to our previous answer

/* 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;
  }
}

And assign it more simply

console.tron = Reactotron;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM