Freshness
Freshness
TypeScript provides a concept of Freshness (also called strict object literal checking) to make it easier to type check object literals that would otherwise be structurally type compatible.
Structural typing is extremely convenient. Consider the following piece of code. This allows you to very conveniently upgrade your JavaScript to TypeScript while still preserving a level of type safety:
However, structural typing has a weakness in that it allows you to misleadingly think that something accepts more data than it actually does. This is demonstrated in the following code which TypeScript will error on as shown:
Note that this error only happens on object literals. Without this error one might look at the call logName({ name: 'matt', job: 'being awesome' })
and think that logName would do something useful with job
where as in reality it will completely ignore it.
Another big use case is with interfaces that have optional members, without such object literal checking, a typo would type check just fine. This is demonstrated below:
The reason why only object literals are type checked this way is because in this case additional properties that aren't actually used is almost always a typo or a misunderstanding of the API.
Allowing extra properties
A type can include an index signature to explicitly indicate that excess properties are permitted:
Use Case: React State
Facebook ReactJS offers a nice use case for object freshness. Quite commonly in a component you call setState
with only a few properties instead of passing in all the properties, i.e.:
Using the idea of freshness you would mark all the members as optional and you still get to catch typos!:
Last updated