This tutorial aims to provide an understanding of type annotations and type inference in TypeScript. TypeScript, a statically typed superset of JavaScript, enforces type checking at compile time, leading to the prevention of potential runtime errors. Two fundamental aspects of TypeScript's static type checking are Type Annotations and Type Inference.
By the end of this tutorial, you will learn:
Prerequisites: Basic knowledge of JavaScript and an understanding of TypeScript is helpful, though not strictly necessary.
Type Annotations in TypeScript are a way of explicitly specifying the type of a variable at the time of declaration.
let message: string;
message = 'Hello World';
In the above code message
is explicitly declared as a string. Trying to assign a non-string value to message
will throw a compile-time error.
TypeScript can often infer types without explicit annotations based on how variables are initialized and used. This is known as Type Inference.
let message = 'Hello World';
In the above code, TypeScript infers message
to be a string because it's initialized with a string.
Best practice: Let TypeScript infer types whenever possible. Use type annotations when the type cannot be inferred.
Example 1: Explicit Type Annotation
let age: number;
age = 25; // This is fine
age = 'Twenty Five'; // This will throw an error as age is of type number
Example 2: Type Inference
let isAdult = true;
// TypeScript infers isAdult to be of type boolean since it is initialized with a boolean value
isAdult = 'yes'; // This will throw an error
Example 3: Function Parameter Type Annotation
function greet(name: string) {
console.log(`Hello, ${name}`);
}
greet('Alice'); // This is fine
greet(123); // This will throw an error as the argument should be a string
In this tutorial, you learned about:
Next steps: Explore more about TypeScript's static types like tuples, enums, and any. Also, understand the concept of Interfaces in TypeScript.
Additional resources:
year
with type number
and assign it your birth year.name
and assign it your name. Let TypeScript infer the type.add
that takes two parameters of type number
and returns their sum.Solutions:
1.
let year: number;
year = 1990;
2.
let name = 'John';
3.
function add(a: number, b: number) {
return a + b;
}
Continue practicing by creating more variables and functions with explicit type annotations and letting TypeScript infer types where possible.