やっぱりCSSはCSSファイルに書きたいので、最近は CSS in JS より classnames とか使っていることが多いです。
しかしその場合、動的なスタイルの変更に弱くなるので、そういったときに使うのがインラインスタイル。ですが、TypeScriptで書いている場合、objectを定義したときに存在しなかったキーを追加しようとすると怒られてしまいます。
「Error: The property 'right' does not exist on value of type '........'」
const WithBadge: React.FunctionComponent<BadgeProps> = ({ children, content, position = 'right' }) => {
const style = {
top: '-0.5em',
background: '#D54A4A',
color: '#fff',
};
if (position === 'right') {
// Error: The property 'right' does not exist on value of type '........'
style.right = '-1.3em';
} else {
// Error: The property 'left' does not exist on value of type '........'
style.left = '-1.3em';
}
style
に型を定義すればよいだけ
TS力が強い人ならこんなことでググる必要もないと思うのですが、自分はまだまだでした。
style
の型を{ [key: string]: string }
とすることで解決しました。
const style: { [key: string]: string } = {
top: '-0.5em',
background: '#D54A4A',
color: '#fff',
};
if (position === 'right') {
style.right = '-1.3em';
} else {
style.left = '-1.3em';
}
参考
How do I dynamically assign properties to an object in TypeScript?