Javascript TypeScript and Static Typing with syntax and examples
TypeScript is a superset of JavaScript that adds optional static typing and other features to improve the development experience. Static typing allows developers to catch errors early and improve code maintainability, thus making it a crucial aspect of TypeScript.
TypeScript Basics
- Variables and Types:
- Declare variables with types using the let and const keywords
- Use type annotations to specify types
- Basic Types:
- Number, String, Boolean, Array, Null, Undefined
- Complex Types:
- Object, Tuple, Enum, Union, Intersection
Syntax:
let name: string = 'John';
let age: number = 30;
let isAdmin: boolean = true;
Type Inference
- TypeScript can automatically infer types without explicit type annotations
- Type inference works for variables, function parameters, and return types
Syntax:
let name = 'John'; // TypeScript infers type as string
Interfaces
- Interfaces define the shape of objects
- Use interfaces to define contracts for objects
Syntax:
interface Person {
name: string;
age: number;
}
let person: Person = {
name: 'John',
age: 30
};
Type Guards
- Type guards narrow the type of a value within a specific scope
- Use type guards to check for specific types or properties
Syntax:
function isString<T>(value: T): value is string {
return typeof value === 'string';
}
let value: string | number = 'Hello';
if (isString(value)) {
console.log(value.toUpperCase()); // TypeScript knows value is a string
}
Generics
- Generics allow functions and classes to work with multiple types
- Use generics to create reusable and flexible code
Syntax:
function identity<T>(arg: T): T {
return arg;
}
let result = identity<string>('Hello'); // TypeScript knows result is a string
By mastering TypeScript and static typing, developers can write more maintainable, scalable, and efficient code. Remember to practice and experiment with different examples to solidify your understanding.
Next Topic:
- Module 12: Advanced TypeScript Concepts
In this module, we will explore advanced TypeScript concepts such as decorators, namespaces, and modules. We will learn how to use these features to write more robust and maintainable code.