Reputation: 15336
This code won't compile:
interface A {
[key: string]?: string
}
While this does:
type Partial<T> = {
[P in keyof T]?: T[P]
}
Why, and how to fix the first one?
P.S.
As a solution it's possible to use Partial
but it doesn't look very nice:
type A = Partial<{
[key: string]: string
}>
Upvotes: 1
Views: 1209
Reputation: 37938
When you use index signature all the keys are optional by default because you're specifying only key's type (string
| number
) and its value type, not the actual required key. So you don't need to add ?
.
interface A {
[key: string]: string
}
Same with type alias:
type A1 = {
[key: string]: string
}
Or Record utility (same as type alias):
type A2 = Record<string, string>;
type Partial<T> = { [P in keyof T]?: T[P] }
is a mapped type. It creates new type based on another type and as in this example can make properties optional. By the way Partial
is included in typescript utility types, no need to redeclare it.
Upvotes: 2