LoginSignup
3
1

More than 5 years have passed since last update.

クラスに Computed Property を設定する時にFlowに叱られないように

Posted at

躓いた所

constructorの中とかでthis[key] = 1とか入れようとするとFlowに叱られる。

例えばこんな感じ。

class A {
  a: number;

  constructor(data: {|x: string|}) {
    this.a = 1;
    this[data.x] = 'value';
    // ^ assignment of computed property/element. Indexable signature not found in
    // ^ A
  }
}

解決

thisを一時的に違う型にする。それには(<var>: <type>)というシンタックスを使う。
例えば今回なら、{[string]: string}というタイプを作ってこんな感じにすれば叱られなくなります。

type ComputedProps = {[string]: string};

class A {
  a: number;

  constructor(data: {|x: string|}) {
    this.a = 1;
    (this: ComputedProps)[data.x] = 'value';
    // No errors!
  }
}

console.log(new A({x: 'aiueo'}));
// A { a: 1, aiueo: 'value' }

Try

https://flow.org/try/#0C4TwD...

3
1
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
3
1