LoginSignup
5
2

More than 5 years have passed since last update.

React with TypeScriptでインラインスタイルでCSS書くときに、objectにそんなプロパティないよって怒られた時の対処法

Posted at

やっぱり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?

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2