In a standard create-react-app
configuration, there’s a third-party component that I can import when needed:
import { Button } from '@mui/material'
// […]
<Button variant="|"></Button>
The library is fully-typed, so hitting Ctrl
+Space
in VSCode when the cursor is at |
will show me a list of possible string variants that I can use. I could add another variant by creating a local component that wraps the @mui/material/Button
:
// LocalComponent.js
import React from 'react'
import { Button } from '@mui/material'
// Do something to actually add a variant called `new`.
export const LocalComponent = React.forwardRef((props, ref) => {
return (
<Button ref={ref} {...props}>
{props.children}
</Button>
)
})
// LocalComponent.d.ts
import type { ButtonProps } from '@mui/material'
interface Props extends ButtonProps {
/** @default 'text' */
variant?: 'text' | 'outlined' | 'contained' | 'new'
}
export declare function LocalComponent(props: Props): React.FunctionComponent
If I import LocalComponent
, I can get intellisense for the new variant, as well as the original Button
’s props. The library also has a feature that allows me to create new variants without having to wrap the library’s components, but I’m having problems with intellisense when I use it—even though the new
variant is implemented, I see only the original variants. The library exposes an interface specifically for module augmentation, so I should be doing something like this:
declare module '@mui/material/Button' {
interface ButtonPropsVariantOverrides {
new: true;
}
}
ButtonPropsVariantOverrides
is supposed to be merged with the variant
property of the interface that defines all props for the Button
, essentially turning it into variant?: 'text' | 'outlined' | 'contained' | 'new'
, but it seems that TypeScript doesn’t see this module augmentation. I tried the following setup:
// jsconfig.json
{
"compilerOptions": {
"baseUrl": "src",
"typeRoots": [
"./src/types", "node_modules/@types"
]
},
"include": ["src"]
}
Not sure if typeRoots
does anything in jsconfig
—it’s not listed as an available option of compilerOptions
, but since jsconfig
is almost tsconfig
, I tried it anyway.
.
├── src/
│ └── types/
│ └── @mui/
│ └── material/
│ └── Button/
│ └── index.d.ts // Contains the module augmentation from above.
└── jsconfig.json
As well as this one:
.
├── src/
│ └── types/
│ └── index.d.ts // Contains the module augmentation from above.
└── jsonfig.json
I also made sure to restart the TS server every time I changed something. Where to put module augmentations in general? Is there anything wrong with how I set up jsconfig.json
? Here’s a CodeSandbox of what I’ve just described.
Thank you for your time.
LocalComponent.d.ts
seems to solve the problem. codesandbox.io/s/xenodochial-dan-sk4wf?file=/src/App.js