Hacker News new | ask | show | jobs
by jakelazaroff 1709 days ago
It’s not true that Record will result in a type where any key is valid. If you pass in a primitive like string, then of course any string will be valid. That’s not Record’s fault; what you’re doing is essentially creating an index signature [1]. If you pass a more restrictive type in as the key, it works as expected:

    type Tips = Record<“foo”, TipObject>;
    const tips: Tips = {}; // error, needs key “foo”
    tips["foo"]; // fine
    tips["bar"]; // error, no key “bar” in tips
It’s worth mentioning that this isn’t just an issue with objects. For example, by default, the index type on arrays is unsafe:

    const arr: number[] = [];
    const first: number = arr[0]; // actually undefined, but typescript allows it
If you do need an index type and want to account for undefined keys, the idiomatic way is the noUncheckedIndexAccess compiler flag [2], which will automatically make any index property access a union with undefined.

[1] https://www.typescriptlang.org/docs/handbook/2/objects.html#...

[2] https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAc...