In TypeScript, there's a pre-defined type called Partial<T>
. It is defines like this:
type Partial<T> = {
[P in keyof T]?: T[P];
}
Apparently, the index signature is marked as optional, and this works. If I try to do the same thing like this:
interface IDictionary<T> {
[ key: string ]?: T
}
TypeScript complains about the ?
. Is this because interfaces may not contain optional fields, or what is the reason for this?
No, typescript interfaces allow optional fields. The reason is it makes no sense, logically.
Partial<T>
is adding a constraint on how the key should look like => P in keyof T
.
If you would remove the ?
here this would mean Partial<T>
is the same as T
.
interface Car {
brand: string;
color: string;
}
// this is exactly the same as the interface declaration below
type PartialCar = Partial<Car>;
// this is exactly the same as the type above
interface PartialCar = {
brand?: string;
color?: string;
}
const carWithoutColor: PartialCar = { brand: "BMW" }
const thisIsStillAPartialCar: PartialCar = {}
For your IDictionary<T>
it's different. You are not adding a constraint on the key (just saying it's any string
). So it makes no sense to say it can be optional because it's anyway optional (in terms of it could be any string
).
In your IDictionary<T>
you are just adding a constraint on the value part which needs to be type of T
.
const numberDictionary: IDictionary<number> = { someStupidKey: 1, oneMoreKey: 2 }
const stringDictionary: IDictionary<string> = { someStupidKeyAWFSAFWAFW: "foo", oneMoreKey: "bar" }
// typescript will assume that "someVariable" is a number
const someVariable = numberDictionary.thisIsUndefined;
// which is why this will not end up in a compile error but a runtime error
const someResult = 1 + someVariable;
As you can see every key is already optional with your declartion of IDictionary<T>
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