Typescript Annotations Assertions Inference
Typescript Annotations Assertions Inference
BY
VIGNESH GOPIRAJ
RENGANATHAN
TODAYS TOPIC:
Today we •ANNOTATIONS,
going to •INFERENCES, and
discuss •
about ASSERTIONS.
Annotations
TypeScript - Type
The following example declares variables with
Annotations different data types:
Type • In the above example, we have an array that has the values 10,
inference in null, 30, and, 40 . TypeScript looks for the most common type to
infer the type of the object. In this case, it picks the one thats is
• Here, the array has values of type number as well as type string. In
such cases, the TypeScript compiler looks for the most common
type to infer the type of the object but does not find any super
type that can encompass all the types present in the array. In such
cases, the compiler treats the type as a union of all types present in
the array. Here, the type would be (string | number) which means
that the array can hold either string values or number values. This
is called union type.
• Lets try to add a new element to the array:
• The compiler accepts the new value since the new value is of type
string which is okay.
• Now, lets try to add a new type to the array which was not already a
part of the array:
• The above code will show a compiler error because boolean is not a part
of union (string | number).
• The return type of a function is also inferred by the returning value. For
example:
• In the above function, return type of the function sum is number. So, the
result can be stored in a number type variable but not a string type
variable.
When we want to change a variable from one type to another such as any to number, String, or
Boolean , we use Type assertion.
So Type assertion is explicitly telling the compiler that we want to treat the entity as a different type. It
allows us to treat any as a number, or number as a string. Type assertion is widely used when we are
migrating codes from JavaScript to TypeScript.
• Typescript Assertions can
Way of
be written using
using Type
2. “as” Keyword
any/unknown must be
Assertions:
specified before using Type
assertions.
Type
assertion
using:
<angular
bracket>
Type Assertion Using “as” Keyword
Example for
Boolean data
type
Difference between the Annotation, Inference and Assertion: