Loading lesson path
TypeScript offers two ways to work with types:
: You explicitly declare the type of a variable
: TypeScript automatically determines the type based on the assigned value
When the initial value might not be the final type
When the type is obvious from the context
Explicit typing means you tell TypeScript exactly what type a variable should be:
// String greeting: string = "Hello, TypeScript!";
Formula
// Number userCount: number = 42;
// Boolean isLoading: boolean = true;// Array of numbers scores: number[] = [100, 95, 98];
Use explicit types for function parameters and return types to make your code more maintainable and self-documenting.// Function with explicit parameter and return types function greet(name: string): string {
return `Hello, ${name}!`;
}
// TypeScript will ensure you pass the correct argument type greet("Alice"); // OK
greet(42); // Error: Argument of type '42' is not assignable to parameter of type 'string'TypeScript can automatically determine (infer) the type of a variable based on its initial value:
// TypeScript infers 'string'
let username = "alice";
// TypeScript infers 'number'
let score = 100;
// TypeScript infers 'boolean[]'
let flags = [true, false, true];
// TypeScript infers return type as 'number'
function add(a: number, b: number) {
return a + b;
}Type inference works best when variables are initialized at declaration. Uninitialized variables have type 'any' by default unless you enable strictNullChecks in your tsconfig.json.
// TypeScript infers the shape of the object const user = {
name: "Alice", age: 30, isAdmin: true
};
// TypeScript knows these properties exist console.log(user.name); // OK
console.log(user.email); // Error: Property 'email' does not existWhile type inference is convenient, being explicit with types can make your code more maintainable, especially in larger codebases or public APIs.Formula
One of TypeScript's main benefits is catching type - related errors during development.Let's look at how TypeScript helps prevent common mistakes.
Explicit Type Mismatch let username: string = "alice";
username = 42; // Error: Type 'number' is not assignable to type 'string'
Implicit Type Mismatch let score = 100; // TypeScript infers 'number'
score = "high"; // Error: Type 'string' is not assignable to type 'number'In JavaScript, the following code would run without errors, potentially causing bugs:
// This is valid JavaScript but can lead to bugs function add(a, b) {
return a + b;
}
console.log(add("5", 3)); // Returns "53" (string concatenation)TypeScript catches these issues at compile time: TypeScript Type Safety function add(a: number, b: number): number {
return a + b;
}
console.log(add("5", 3)); // Error: Argument of type 'string' is not assignable to parameter of type 'number'While TypeScript's type inference is powerful, there are cases where it can't determine the correct type. In these situations, TypeScript falls back to the any type, which disables type checking.