Issue
I have a CSSProperties
style property. I would like to access a custom property as an indexer. Not having any luck.
style: {
'--primary-color': '#ff0000',
color: '#ff0000',
} as React.CSSProperties
This works:
console.log(style['color'])
This does not:
console.log(style['--primary-color'])
nor does this:
console.log(style['var(--primary-color)'])
Error is:
Element implicitly has an 'any' type because expression of type '"var(--primary-color)"' can't be used to index type 'CSSProperties'.
Property 'var(--primary-color)' does not exist on type 'CSSProperties'
Any ideas?
Solution
Since even satisfies
in 4.9+ doesn't work (gives same error as without), I suppose the only canonical solution now is to use a generic function:
const STYLE = <T extends React.CSSProperties>(t: T) => t;
It'll still check if it matches CSSProperties, and you can add in other properties, but it's a little longer:
const obj = {
style: STYLE({
"--primary-color": "#ff0000",
color: "#ff0000",
}),
};
obj.style["--primary-color"];
Answered By - caTS
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.