Weak Type Detection
TypeScript 2.4 introduces the concept of “weak types”.Any type that contains nothing but a set of all-optional properties is considered to be weak.For example, this Options
type is a weak type:
interface Options {
data?: string;
timeout?: number;
maxRetries?: number;
}
In TypeScript 2.4, it’s now an error to assign anything to a weak type when there’s no overlap in properties.For example:
function sendMessage(options: Options) {
// ...
}
const opts = {
payload: "hello world!",
retryOnFail: true,
}
// Error!
sendMessage(opts);
// No overlap between the type of 'opts' and 'Options' itself.
// Maybe we meant to use 'data'/'maxRetries' instead of 'payload'/'retryOnFail'.
You can think of this as TypeScript “toughening up” the weak guarantees of these types to catch what would otherwise be silent bugs.
Since this is a breaking change, you may need to know about the workarounds which are the same as those for strict object literal checks:
- Declare the properties if they really do exist.
- Add an index signature to the weak type (i.e.
[propName: string]: {}
). - Use a type assertion (i.e.
opts as Options
).