Typescript 2.6 -> Extend type definition for exter

2019-08-23 15:38发布

I'm using the library material-ui and I'm currently running the v1.0.0-beta. They updated the library yesterday to v1.0.0-beta.28 but did not update the type definitions so my code fails at run time but not at compile time.

From Chrome:

webpack-internal:///./node_modules/material-ui/styles/colorManipulator.js:80 Uncaught TypeError: Cannot read property 'charAt' of undefined at decomposeColor (webpack-internal:///./node_modules/material-ui/styles/colorManipulator.js:80) at lighten (webpack-internal:///./node_modules/material-ui/styles/colorManipulator.js:226) at createPalette (webpack-internal:///./node_modules/material-ui/styles/createPalette.js:144) at Object.createMuiTheme (webpack-internal:///./node_modules/material-ui/styles/createMuiTheme.js:71) at StartPage.render (webpack-internal:///./Features/Client/StartPage/index.tsx:106) at finishClassComponent (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:7873) at updateClassComponent (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:7850) at beginWork (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:8225) at performUnitOfWork (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:10224) at workLoop (webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:10288)

https://github.com/mui-org/material-ui/releases/tag/v1.0.0-beta.28

Looking at the release notes I can see that the palette object has changed primary and secondary colors and it is a breaking change.

I then read about module augmentation and tried to extend the Color object in this case that needs new properties.

https://github.com/Microsoft/TypeScript/issues/10859#issuecomment-246496707

http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation

I extended it like this:

import { Color } from 'material-ui'

declare module 'material-ui' {
  export interface Color {
    light?: string
    main?: string
    dark?: string
  }
}

enter image description here

Visual Studio picks it up and builds but when I try to run webpack I get the following error:

TS2339: Property 'main' does not exist on type 'Color'.

Why does this happen?

1条回答
forever°为你锁心
2楼-- · 2019-08-23 16:21

Turns out the error came from using a shared project and because of this type definitions were not loaded correctly, even if the module augmentation was present in the shared project as well. Will have to check our structure because it will probably lead to more errors in the future.

查看更多
登录 后发表回答