Record
processes the combination of keys provided in the key argument, forming an object type that necessitates all of those keys. When you inspect ErrorMessages
in your IDE or the TypeScript playground, you'll encounter the detailed definition, shedding light on the issue:
type ErrorMessages = {
[x: number]: string;
default: string;
}
Similarly, using
Record<"a" | "b", string>
mandates inclusion of
both a
and
b
properties.
To address this, you can directly define ErrorMessages
as an object type while explicitly making the default
optional with a postfix ?
, like so:
type ErrorMessages = {
[key: number]: string;
default?: string;
};
This approach facilitates both assignments:
const text1: ErrorMessages = { 403: "forbidden" };
const text2: ErrorMessages = { default: "something else" };
This also permits multiple messages, which appears appropriate given the type name ErrorMessages
(plural):
const text3: ErrorMessages = {
default: "something else",
403: "forbidden",
};
...while restricting other string keys:
// Generates error as intended
const text4: ErrorMessages = { foo: "bar" };
// ^^^^^^^^^^ Type '{ foo: string; }' is not assignable to type 'ErrorMessages'.
// Object literal may only specify known properties, and 'foo' does not exist in type 'ErrorMessages'. (2322)
Access Playground here