躓いた所
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' }