このような型付をみつけて
const a: Record<string, string> = {
doorToDoor: "delivery at door",
airDelivery: "flying in",
specialDelivery: "special delivery",
inStore: "in-store pickup",
};
あれこれは
{[key: string]: string}
と同じ意味じゃないのか
なぜ、Record
を使っているのか...
と思い調べた.
一緒。
Difference between index signature and Record for empty object?
要約すると
Record<string, string>
と{[key: string]: string}
は同じで意味で
わざわざRecord<string, string>
と書くのは他の開発者を迷わせてしまうかもしれない
ので
{[key: string]: string}
で書こうね。
As you note, K has a purpose... to limit the property keys to particular values.
If you want to accept all possible string-valued keys, you could do something like Record<string, T>,
but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.
話はそれるが、
そもそも
{[key: string]: string}
は
string値型を持っているならどんなkey
でも入ってしまうためよろしくない。
const a: Record<string, string> = {
doorToDoor: "delivery at door",
airDelivery: "flying in",
specialDelivery: "special delivery",
inStore: "in-store pickup",
};
const aa:string = a["name"] // undefined
aa
には実際はundefined
が入っていて、runtimeエラーになりそうだからだ
なので上記の例でいうと、わかっている場合
に限るが
type A = Record<"doorToDoor" | "airDelivery" | "specialDelivery" | "inStore", string>
const a: A = {
doorToDoor: "delivery at door",
airDelivery: "flying in",
specialDelivery: "special delivery",
inStore: "in-store pickup",
};
の方が型安全で、他の追加keyを許さない。
type B = Record<"b" | "c", string>["b"]
// 当然BはT(string)
type B = Record<"b", string>
function b(obj: B){
return obj
}
b({b: "b", c: "c"})// Error
リテラルはこの場合でもダメ
type B = Record<"b", string>
function b(obj: B){
return obj
}
const imp = {b: "b", c: "c"}
b(imp) // ok TypeScriptのコンパイラは必須な値のみcheckする
function b(obj: B){
return obj.c // ここで参照するとError
}
see: [excess properties](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)
// type B = Record<"b" | "c", string> で解決