简体   繁体   中英

Add property to React Typescript Interface

I think I am using the correct syntax/terms, if not please let me know. I am transitioning a project to typescript and it's going ok -- The index.tsx file currently sets React.icons to an object of custom icons from the coreui library. Using typescript, Property 'icons' does not exist on type 'typeof React'.

I think I need to extend the React interface/type declaration to include icons as a typeof React .

The error is present under the first icons in React.icons = icons from the code below. If anyone can point me in the right direction, i'd be happy.

import "react-app-polyfill/ie11"; // For IE 11 support
import "react-app-polyfill/stable";
import "core-js";
import "./polyfill";
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

import store from "./store";

import { icons } from "./assets/icons";

interface IReactIcons extends React {
  icons: object;
}

React.icons = icons;

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

serviceWorker.unregister();

Trying to add Module Augmentation below:

import "react-app-polyfill/ie11"; // For IE 11 support
import "react-app-polyfill/stable";
import "core-js";
import "./polyfill";
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

import store from "./store";

import { icons } from "./assets/icons";

declare module "react" {
  interface React {
    icons: {};
  }
}

React.icons = icons;

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

serviceWorker.unregister()

You can't use modal augmentation because as it is stated it the docs:

  1. You can't declare new top-level declarations in the augmentation — just patches to existing declarations.
  2. Default exports also cannot be augmented, only named exports

Good new is that you can use global augmentation instead

declare global {
  namespace React {
    let icons:any;
  }
}

If you know what types your icons are use it instead of any

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