How to extends `CSSProperties` in react project
TypeScript expects specific types "flex"
and "column"
, but without any additional work, it receives string
for both, which is too wide and non-descript. You can see the same error happen here:
declare const value: string
const a: "a" = value // errors, `string` can't be assigned to the more specific `"a"`
There are a few solutions here. I think the most elegant one is as const
, so it'll treat your object values as their specific literal types. Also make sure your TS version is up to date to use this.
const styles = {
promAlert: {
display: 'flex',
flexDirection: 'column',
},
} as const
Alternatively, you can declare your style objects separately and have them typechecked by the CSSProperties
interface. This gives autocomplete on each property, but this can't (easily) be done as a single full object.
const promptAlert: React.CSSProperties = {
display: 'flex',
flexDirection: 'column'
}
// you can re-assign all of your styles into a single object if you want,
// but I think it would be easier to access `promptAlert` directly at this point
const styles = {
promptAlert,
}
Other less ideal solutions:
{ [key: string]: React.CSSProperties }
: this doesn't perform type checking on the name of each style, so you can dostyles.abcdef
without any errorCasting each style
as React.CSSProperties
: this doesn't catch errors in the styles themselves, e.g. you could typodisplay: "fleex"
Defining styles
type as shown below will preserve type check on your all CSS classes and their properties:
const styles: { [key: string]: React.CSSProperties } = {
promAlert: {
display: 'flex',
flexDirection: 'column'
}
};
Change
const styles = {
promAlert: {
display: 'flex',
flexDirection: 'column'
}
};
To
const styles = {
promAlert: {
display: 'flex' as 'flex',
flexDirection: 'column' as 'column'
}
};
This tells TypeScript that these values are literals.