Defining variables with specific types in TypeScript is straightforward. You can specify a variable's type by appending a colon (:) followed by the type name after the variable name. This enables TypeScript to enforce type safety by catching potential type errors during compilation.
Example
Suppose we want to define a variable representing a user's age, which we know should be a number. In TypeScript, you can define it as:
typescriptlet age: number; age = 30; // Correct
Here, the age variable is explicitly declared as a number type, meaning that if you attempt to assign a non-numeric value to age, the TypeScript compiler will report an error:
typescriptage = "thirty"; // Error: Type 'string' is not assignable to type 'number'.
More Complex Types
TypeScript also supports more complex type definitions, such as arrays, objects, and tuples. For example, if you want to define an array containing only strings, you can do:
typescriptlet fruits: string[] = ["apple", "banana", "cherry"];
If you want to define an object, you can specify the types of its properties:
typescriptlet person: { name: string; age: number } = { name: "Alice", age: 25 };
Using Interfaces or Type Aliases
For more complex data structures, you can define types using interfaces (interface) or type aliases (type), which simplify type reuse and extension.
typescriptinterface User { name: string; age: number; } let user: User = { name: "Bob", age: 30 };
In this example, we define a User interface and use it to declare the type of the user variable.
Summary
By explicitly defining variable types in TypeScript, you can leverage its type system to improve code maintainability and reduce runtime errors. These type definitions can be simple primitive types or complex interfaces or type aliases, depending on your specific needs. This type safety feature is one of TypeScript's main advantages.