Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 482
alexmngn Avatar asked Jun 26 '17 16:06

alexmngn


2 Answers

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
    }
}
like image 188
Saravana Avatar answered Nov 12 '22 03:11

Saravana


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;
like image 1
Leo Avatar answered Nov 12 '22 04:11

Leo