解決したいこと
{'name':'j', 'age':20}のようなオブジェクトから値を読み出す時に、keyに変数を用いたい
困っていること
js
1const John = {'name':'j', 'age':20} 2const str = 'name';
というコードで、John[str]
と書くことで値'j'
を取り出したいがエラーになる。
詳細
以下のコードは期待通りに振る舞う。
js
1class Square extends React.Component<Props> { 2 render() { 3 const john:{name:string,age:number} = {name:'j',age:20} 4 const johnName = john['name'] 5 return ( 6 <button className="square" onClick={this.props.onClick}> 7 {johnName} 8 </button> 9 ); 10 } 11}
Squareコンポーネントはclass内で定義した変数johnNameを表示する四角いボタンです。Johnのnameであるjが表示されており、期待通りの振る舞いです。
ここで'name'を変数にして以下のコードに書き換えます。
js
1class Square extends React.Component<Props> { 2 render() { 3 const john:{name:string,age:number} = {name:'j',age:20} 4 const v:string = 'name' //変更 5 const johnName = john[v] //変更 6 return ( 7 <button className="square" onClick={this.props.onClick}> 8 {johnName} 9 </button> 10 ); 11 } 12}
これは以下のようなエラーとともに失敗します。
Failed to compile. /Users/username/Desktop/react/Syogi/syogi/src/App.tsx TypeScript error in /Users/username/Desktop/react/Syogi/syogi/src/App.tsx(24,22): Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ name: string; age: number; }'. No index signature with a parameter of type 'string' was found on type '{ name: string; age: number; }'. TS7053 22 | const john:{name:string,age:number} = {name:'j',age:20} 23 | const v:string = 'name' > 24 | const johnName = john[v] | ^ 25 | return ( 26 | <button className="square" onClick={this.props.onClick}> 27 | {johnName}
Qiitaの記事によるとこの記法で動くみたいですが、TypeScriptの場合はうまくいかないようです。
TypeScriptでこれを解決している記事も見当たらず、質問させていただいた次第です。
よろしくお願いいたします。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/07/29 14:54