TypeScript, a superset of JavaScript, introduces static types to the dynamically-typed world of JavaScript. This feature allows developers to catch errors early during the development process and improve the maintainability of their code. In this guide, we'll explore the various types available in TypeScript and how they can be used to write more robust and error-free code.
let isDone: boolean = false;
2. **Number**
- Represents both integer and floating-point numbers.
```typescript
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
String
let color: string = "blue";
Array
let list: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];
Tuple
let x: [string, number];
x = ["hello", 10];
Enum
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
Any
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
Void
function warnUser(): void {
console.log("This is my warning message");
}
Null and Undefined
let u: undefined = undefined;
let n: null = null;
Union Types
let code: string | number;
code = 123; // OK
code = "ABC"; // OK
Intersection Types
interface Person {
name: string;
}
interface Employee {
employeeId: number;
}
type EmployeePerson = Person & Employee;
let newEmployee: EmployeePerson = {
name: "John",
employeeId: 1234
};
Type Aliases
type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
Literal Types
let specificString: "hello" = "hello";
Generics provide a way to create reusable components that work with any data type. This allows for type-safe operations without sacrificing flexibility.
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("myString"); // type of output will be 'string'
Type assertions allow you to override TypeScript's inferred type with a specific type.
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Understanding and effectively using TypeScript types can significantly improve the quality and maintainability of your code. By leveraging the power of TypeScript's type system, you can catch errors early, enhance code readability, and build more robust applications. Whether you're dealing with basic types, advanced types, or generics, mastering TypeScript types is an essential skill for any modern web developer.