TypeScript Basics Variables and Types Simplified

TypeScript enhances JavaScript by adding static types, which help catch errors early and improve code quality. This article will simplify the basics of TypeScript variables and types, providing a clear understanding for beginners.

Understanding Variables in TypeScript

In TypeScript, variables are declared similarly to JavaScript but with the added benefit of type annotations. This allows you to specify what kind of data a variable should hold.

Declaring Variables

You can declare variables using let, const, and var. However, let and const are recommended for their block-scoping features.

let age: number = 25;
const name: string = "Alice";

Basic Types in TypeScript

TypeScript provides several basic types to define the kind of data a variable can hold:

  • Number: Represents numeric values, including integers and floating-point numbers.
  • String: Represents textual data.
  • Boolean: Represents true or false values.
  • Array: Represents a collection of values of a specific type.
  • Object: Represents a collection of key-value pairs.

Number Example

let count: number = 100;

String Example

let greeting: string = "Hello, World!";

Boolean Example

let isActive: boolean = true;

Array Example

let scores: number[] = [90, 80, 70];

Object Example

let user: { name: string, age: number } = {
  name: "John",
  age: 30
};

Type Inference

TypeScript can automatically infer the type of a variable based on its initial value. This means you don’t always need to explicitly specify the type, although doing so can make your code clearer.

Type Inference Example

let age = 25; // TypeScript infers 'age' as number
age = "hello"; // Error: Type 'string' is not assignable to type 'number'

Type Annotations

Type annotations allow you to explicitly define the type of a variable. This helps ensure that values assigned to variables conform to the expected type.

Type Annotation Example

let isLoggedIn: boolean = false;

Conclusion

Understanding variables and types is fundamental to using TypeScript effectively. By leveraging TypeScript's type system, you can write more reliable and maintainable code. Begin with basic types, explore type inference, and use type annotations to ensure your code adheres to expected data structures.

With these basics, you're on your way to mastering TypeScript and harnessing its full potential for building robust applications.