LoginSignup
0
0

More than 1 year has passed since last update.

変数名に動的にアクセスする

Posted at

概要

数字のプロパティ名(a1やa2など)にテンプレートリテラルでアクセスするとエラーがおきてうまく行きませんでした。
たとえば以下のような書き方です。

NGパターン

interface contentsModel {
  a1: string;
  a2: string;
  a3: string;
}

const contents: contentsModel = {
  a1: 'コンテンツA',
  a2: 'コンテンツB',
  a3: 'コンテンツC',
}
const num = "1"
const value = contents[`a${num}`]; // ←この書き方だとうまく行かない

エラー内容

Element implicitly has an 'any' type because expression of type '`a${num}`' cant be used to index type 'model';

OKパターン

原因
・numが文字列型ではなく、文字列を含んだ数値型とみなされるためのようでした。

以下のように[key: string]を型につけて、明示的にプロパティの方を示すことによって解決できました。

interface contentsModel {
  + [key: string]
  a1: string;
  a2: string;
  a3: string;
}
0
0
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
0
0