Exploring Basic Data Types in TypeScript
Tags: typescript, webdev, javascript, programming
Published: 2024-05-28 06:14:07

TypeScript is a powerful, statically typed superset of JavaScript that helps developers write more robust and maintainable code. Understanding the basic data types in TypeScript is essential for beginners to leverage its full potential. In this article, we'll explore the fundamental data types: `string`, `number`, `array`, `object`, `null`, `undefined`, `function`, `never`, `type alias`, and `type alias in function`.

## 1. String
A `string` in TypeScript is used to represent textual data. It's a sequence of characters and is enclosed in single ('), double ("), or backticks.

```typescript
let message: string = "Hello, TypeScript!"
console.log(message) // output: "Hello, TypeScript!"
```

You can also use template literals (enclosed by backticks) to embed expressions:
```typescript
let userName: string = "Alice";
let greeting: string = `Hello, ${userName}!`;
console.log(greeting) // output: Hello, Alice!
```

## 2. Number
A `number` in TypeScript can represent both integer and floating-point values. TypeScript uses the number type to cover all numeric values, including special values like Infinity and `NaN`.

```typescript
let myNumber: number = 5;
let myFloat: number = 19.71;
let myInfinity: number = Infinity;
console.log(myNumber) // output: 5
console.log(myFloat) // output: 19.71
console.log(myInfinity) // output: Infinity
```

## 3. Array 
An `array` in TypeScript is used to store a collection of elements of a specific type. You can define an array using the `Array<type>` syntax or the `type[]` syntax.

```javascript
let myArray: number[] = [1, 2, 3, 4, 5];
let myStringArray: Array<string> = ["one", "two", "three"];
console.log(myArray); // Output: [1, 2, 3, 4, 5]
console.log(myStringArray); // Output: ["one", "two", "three"]
```

## 4. Object 
An `object` in TypeScript is a collection of key-value pairs, where the keys are strings (or symbols) and the values can be of any type. You define the shape of an object using an interface or a type alias.

```typescript
let myObject: { name: string, age: number } = { name: "John", age: 30 };
console.log(myObject); // Output: { name: "John", age: 30 }
```

Using an interface:
```typescript
interface Person {
  name: string;
  age: number;
}
let anotherPerson: Person = { name: "Jane", age: 25 };
console.log(anotherPerson); // Output: { name: "Jane", age: 25 }
```

## 5. Null & Undefined
`null` and `undefined` are special types that represent the absence of a value. `null` is often used to explicitly indicate the absence of a value, whereas `undefined` typically means a variable has been declared but not yet assigned a value.

```typescript
let myNull: null = null;
let myUndefined: undefined = undefined;
console.log(myNull); // Output: null
console.log(myUndefined); // Output: undefined
```

Variables without an initial assignment default to `undefined`:

```typescript
let notAssigned;
console.log(notAssigned); // Output: undefined
```

## 6. Function
A `function` in TypeScript is a block of code that performs a specific task. Functions can accept parameters and return a value. TypeScript allows you to define the types of the parameters and the return type.

```typescript
function greet(name: string): string {
  return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!
```

A function with no return value can be specified with the `void` return type:

```typescript
function logMessage(message: string): void {
  console.log(message);
}
logMessage("This is a message."); // Output: This is a message.
```

## 7. Never
The `never` type represents values that never occur. It's typically used for functions that always throw an error or functions that never return.

```typescript
function error(message: string): never {
  throw new Error(message);
}
try {
  error("Something went wrong!");
} catch (e) {
  console.error(e); // Output: Error: Something went wrong!
}
```

A function that never returns (infinite loop):

```typescript
function infiniteLoop(): never {
  while (true) {}
}
```

## 8. Type Alias
A type alias creates a new name for a type. This can be especially useful for simplifying complex type definitions or when you want to give a type a meaningful name.

```typescript
type Point = { x: number, y: number };
let myPoint: Point = { x: 10, y: 20 };
console.log(myPoint); // Output: { x: 10, y: 20 }
```

Using a type alias for union types:

```typescript
type ID = number | string;
let userId: ID = 101;
let anotherId: ID = "user101";
console.log(userId); // Output: 101
console.log(anotherId); // Output: user101
```

## 9. Type Alias in Function
Type aliases can be used in function signatures for better readability and maintainability. This allows you to reuse complex type definitions across multiple functions.

```typescript
type Greeting = (name: string) => string;
const sayHello: Greeting = (name) => `Hello, ${name}!`;
console.log(sayHello("Bob")); // Output: Hello, Bob!
```

Combining type aliases with objects:

```typescript
type Person = { name: string, age: number };
type Introduce = (person: Person) => string;

const introduce: Introduce = (person) => `My name is ${person.name} and I am ${person.age} years old.`;
console.log(introduce({ name: "Charlie", age: 28 })); // Output: My name is Charlie and I am 28 years old.
```

## Conclusion
Understanding the basic data types in TypeScript is crucial for writing effective and type-safe code. These types form the foundation upon which more complex types and structures are built. By mastering `string`, `number`, `array`, `object`, `null` & `undefined`, `function`, `never`, and `type aliases`, you'll be well-equipped to handle a wide range of programming scenarios. TypeScript’s type system not only helps catch errors early but also makes your code more readable and maintainable. As you continue to explore TypeScript, you'll find that these basics will serve as a strong foundation for more advanced concepts and techniques.

Follow me on: [LinkedIn](https://www.linkedin.com/in/iamnahidul-islam) [Portfolio](https://nahidul-islam-fahim.web.app)