In TypeScript, explicitly specifying variable types is done by appending a colon and the type name after the variable name. This approach enhances code clarity and can detect potential type errors during compilation. Here are some specific examples demonstrating how to specify variable types in TypeScript:
-
Basic Types: When you want to specify a variable as a primitive type, such as numbers, strings, or booleans, you can write:
typescriptlet age: number = 30; let name: string = "Alice"; let isStudent: boolean = true; ``n Here, `age` is specified as `number` type, `name` is `string` type, and `isStudent` is `boolean` type. -
Arrays: If you want to specify an array where all elements are of a specific type, you can use the type followed by
[], or the genericArray<element type>:typescriptlet scores: number[] = [75, 82, 90]; let fruits: Array<string> = ["apple", "banana", "cherry"]; ``n Here, `scores` is an array of numbers, and `fruits` is an array of strings. -
Interfaces and Objects: If you want to specify an object with a specific shape (properties and their types), you typically use interfaces:
typescriptinterface User { id: number; name: string; email?: string; // Optional property } let user: User = { id: 1, name: "John Doe", email: "john.doe@example.com" }; ``n Here, the `User` interface requires `id` and `name` properties, with `email` being optional. The variable `user` is specified as `User` type. -
Function Types: In TypeScript, you can specify types for function parameters and return values:
typescriptfunction add(x: number, y: number): number { return x + y; } let result: number = add(5, 3); ``n The `add` function is defined to accept two `number` type parameters and return a `number` type value.
By explicitly specifying types in TypeScript, we can leverage the type system to enhance code robustness and maintainability while reducing runtime errors.