LoginSignup
0
0

More than 1 year has passed since last update.

Index signature(インデックス型)~あのObjectの型を使いたい~

Posted at

Index signature(インデックス型)とは

参考: https://typescript-jp.gitbook.io/deep-dive/type-system/index-signatures

JavaScript(TypeScript)のObjectは、他のJavaScriptオブジェクトへの参照を保持し、文字列でアクセスできます。

コードで実際に見てみましょう

通常

export default class Test {
  public static id: number = 1
}

const id: number = Test.id

index signatureを使う場合

export default class Test {
  public static id: number = 1
}

const id: Test['id'] = Test.id

このようにobject[property名]でそのオブジェクトのプロパティーの型を使うことができます。

Object.propertyを通した値のみしか入れられないようにすることは可能か?

理想

class a {
  public static a: number = 1
}
const b: a['number'] = 1 // error
const c: a['number'] = a.a // ok

現実

class a {
  public static id: number = 1
}
const b: a['id'] = 1 // ok
const c: a['id'] = a.a // ok

結論: できない

Object.propertyを積極的に使うべきか?

使える場面もあるけど、私は基本使わない
DDDの概念の値Objectで別途型を構成した方がいい気がする

type AId = number
class Klass {
  public static id: AId = 1
}
const b: AId = 1 // ok
const c: AId = Klass.id // ok
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