I have experience with styled-components "themes" and how they work by defining custom theme properties for TypeScript autocompletion within styled components. The process involves extending the DefaultTheme interface with our custom theme properties like this:
import { MyTheme } from '~/configurations'
declare module 'styled-components' {
interface DefaultTheme extends MyTheme {}
}
In the configuration file ./configurations/index.ts
, we define the custom theme properties as follows:
const theme = {
fonts: {
font1: 'foo'
},
colors: {
red: 'bar'
}
}
export type MyTheme = typeof theme
The DefaultTheme then dynamically inherits these properties from our custom theme, allowing us to type everything in styled-components according to our theme.
However, when trying to implement similar functionality from scratch, I encountered some issues. Here is an example of a TypeScript library I created, called Halt.js:
import { CustomError } from 'ts-custom-error'
// Rest of the code...
In the Halt.js library, there is a HaltList that I want to inject dynamic properties into to enable TypeScript autocompletion:
halt('
To achieve this, I define custom error codes in a separate file (./configurations/errors
) and attempt to extend the HaltList interface:
import { HaltType } from './configurations/errors'
declare module '@lancejpollard/halt.js' {
export interface HaltList extends HaltType {}
}
Despite my efforts, the autocomplete feature doesn't seem to be working properly. How can I ensure that the extended HaltList interface includes all the custom properties, such as missing_property
, and throws errors for undefined properties?
Update
My usage scenario involves defining custom error codes in Halt.js and using them in other files:
// Code snippet
Although autocompletion works while writing code, assigning the custom properties to Halt.list generates an error. To resolve this, I tried explicitly defining HALT as HaltList:
import { Halt, HaltList } from "@lancejpollard/halt.js";
const HALT: HaltList = {
// ... remaining code
Unfortunately, this caused the autocomplete feature to break with an error message stating:
Argument of type 'string' is not assignable to parameter of type 'never'.
This issue occurs at the location of halt('missing_property')
.