Reputation: 5294
I would like to make the dynamic key item
optional. Adding ?
creates an error.
type Example = {
name?: string;
[item: string]?: unknown; // error: TS1131: Property or signature expected.
};
Upvotes: 2
Views: 2423
Reputation: 144
You could create a type for the dynamic item and make it optional using Partial
like below.
type DynamicItemtype = {
[item: string]: unknown;
}
Then add both types into another type as an intersection type
like
type Example = {
name?: string
}
type CombinedTypes = Example & Partial<DynamicItemtype>
Upvotes: -1
Reputation: 33921
You can use the type utilities Partial
and Record
to create the type you want:
type Example = Partial<Record<string, unknown>> & { name?: string };
declare const example: Example;
example.name; // string | undefined
example.anyOtherProperty; // unknown
Upvotes: 5