Typescript 2.6 -> Extend type definition for external library with module augmentation -> TS2339: Property '' does not exist on type ''

白昼怎懂夜的黑 提交于 2019-12-11 21:22:29

问题


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
  }
}

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:


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.



来源:https://stackoverflow.com/questions/48260011/typescript-2-6-extend-type-definition-for-external-library-with-module-augmen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!