Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kenmori/c75aa4192c272605d8f46c249d5a468d to your computer and use it in GitHub Desktop.
Save kenmori/c75aa4192c272605d8f46c249d5a468d to your computer and use it in GitHub Desktop.
【TypeScript】インデックスシグネチャの型定義。string、number

【TypeScript】インデックスシグネチャの型定義。string、number

@bukotsunikki

1.初期化時に指定

let obj:{ [key: string]: string} = {}

let a = obj["a"];

console.log(a) // undefined

playground

2.存在しないプロパティにアクセスした際にエラーになってほしい

type Index = "a"

let obj:{ [key: Index]: string} = {} // Index型しか許容しない
// Error An index signature parameter type must be 'string' or 'number'.
// indexはstringかnumber型

let a = obj["a"];

console.log(a) // undefined

playground

3.オブジェクトの中のプロパティ型をkeyにする

type Index = "a"

let obj:{ [key in Index]: string} = {}
// 初期化時に満たされなくてはいけないようになってしまった
// Property 'a' is missing in type '{}' but required in type '{ a: string; }'.
let a = obj["a"];

console.log(a) // undefined

playground

4.オプショナルに指定して初期値はオブジェクトリテラルにする

type Index = "a"

let obj:{ [key in Index]?: string} = {}

let a = obj["a"];

console.log(a) // undefined

playground

5.存在しないプロパティにアクセスすると推論はanyになる

type Index = "a"

let obj:{ [key in Index]?: string} = {}

let a = obj["b"]; // anyとして推論

console.log(a) // undefined

playground

6.存在しないobjのプロパティを代入しようとするとErrorになる

type Index = "a"

let obj:{ [key in Index]?: string} = {}

obj = {b: "fafa"} // Error

console.log(obj) // undefined

playground

7. プロパティが指定されている as

type Index = "a"

let obj = {} as { [key in Index] : string }

obj = { b: "fafa" } // Error

console.log(obj) // undefined

playground

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment