配列がRecord型…という思わぬ罠になる時があるので注意.
例
type N2S = Record<number, string>; // No error. Both are valid. const obj: N2S = { 0: "hello" }; const ary: N2S = ["hello"]; // Reasonable const obj1 = obj[0]; const ary1 = ary[0];
要素へのアクセスにはdot記法(obj.0
)とブラケット記法(obj[0]
)がある。
要素名がNumberのときdot記法が禁じられているため、配列は一切のdot記法が利用できない。
でも意味論として確かにRecord<number, _>になっている(ブラケット記法がその証拠).
罠
ハマったことのある罠(普通は起きない).
要素削除
// array const ary = ["hello", "world", "!!"]; delete ary[1]; JSON.stringify(ary); // '["hello",null,"!!"]' // object const obj = {0:"hello", 1:"world", 2:"!!"}; delete obj[1]; JSON.stringify(obj); // '{"0":"hello","2":"!!"}'
配列だと要素削除はnull
化だが、オブジェクトだとattributeの存在が消える.
Immerとかの関係でdeleteを使う際に注意.