I have the following code
let elements : Record<MediaType, Person[]> = {};
I get the following error for the line above, where I initialize elements to an empty object.
Type '{}' is missing the following properties from type 'Record<ElementType, Person[]>': "application/vnd.element.animation+dcx", "application/vnd.element.audio+dcx", and 19 more.
What I'm I doing wrong?
Type Record is defined as follows in lib.es5.d.ts:
type Record<K extends keyof any, T> = {
[P in K]: T;
};
// keyof any = string | number | symbol
Thus type RecordWithMediaTypeKey defined as:
type MediaType = "CD" | "Stream"
type RecordWithMediaTypeKey = Record<MediaType, string>
is equivalent to:
type RecordWithMediaTypeKey = {CD: string, Stream: string}
Note that the keys are not optional, which explains your error.
If you want optional keys, you may use: Partial<Record<MediaType, string>>
I think the confusion comes from the fact that:
type RecordWithStringKey = Record<string, string>
is equivalent to:
type RecordWithStringKey = {
[x: string]: string;
}
Note the usage of Index signature.
TS Playground
You are setting elements to an empty object that is expecting an object with all of the keys defined in MediaType. Assuming you are not planning to define everything in the Record, you can try skirting around this by using the Partial utility type.
let elements : Partial<Record<MediaType, Person[]>> = {};
It is typically used here when not expected to define every Record Key in the object. If you plan on doing that, define the object while it is being created to avoid having to use the Partial type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With