var opts: {n?: number; s?: string;};
opts = {n: 2}; // Ok
opts = {s: 'x'}; // Ok
opts = {}; // Ok
opts = {z: 3}; // Ok, but shouldn't this be an error?
I want the opts object to accept none or any of the declared
optional properties (but no others), but it accepts other undefined
properties i.e. the declaration is equivalent to opts: {};, is this
a bug?
If it’s not a bug how can you construct such a declaration?
Part of the beauty of TypeScript is that it is quite clever at deciding whether an object can be coerced into another type.
You declaration for
optsactually has no requirements because both properties are optional, so any any object is compatible with this type. To be compatible, an object must contain all required properties – and in this case there are no required properties.This is clearer if we look at an adjusted example that does require a property:
So this means an object is considered a sub-type of another object if it supports at least the required properties.
That deals with setting the object. Now if you consider using the object you’ll see where the power lies. Because the type promises only
nands(andain my example), the code calling properties onncan only ask for these properties. The additional properties cannot be accessed:So we still have type safety, because we can only use the properties in the type declaration – not the additional properties.