DEV Community

Cover image for Exploring Basic Data Types in TypeScript
Nahidul Fahim
Nahidul Fahim

Posted on • Updated on

Exploring Basic Data Types in TypeScript

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.

let message: string = "Hello, TypeScript!"
console.log(message) // output: "Hello, TypeScript!"
Enter fullscreen mode Exit fullscreen mode

You can also use template literals (enclosed by backticks) to embed expressions:

let userName: string = "Alice";
let greeting: string = `Hello, ${userName}!`;
console.log(greeting) // output: Hello, Alice!
Enter fullscreen mode Exit fullscreen mode

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.

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
Enter fullscreen mode Exit fullscreen mode

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.

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"]
Enter fullscreen mode Exit fullscreen mode

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.

let myObject: { name: string, age: number } = { name: "John", age: 30 };
console.log(myObject); // Output: { name: "John", age: 30 }
Enter fullscreen mode Exit fullscreen mode

Using an interface:

interface Person {
  name: string;
  age: number;
}
let anotherPerson: Person = { name: "Jane", age: 25 };
console.log(anotherPerson); // Output: { name: "Jane", age: 25 }
Enter fullscreen mode Exit fullscreen mode

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.

let myNull: null = null;
let myUndefined: undefined = undefined;
console.log(myNull); // Output: null
console.log(myUndefined); // Output: undefined
Enter fullscreen mode Exit fullscreen mode

Variables without an initial assignment default to undefined:

let notAssigned;
console.log(notAssigned); // Output: undefined
Enter fullscreen mode Exit fullscreen mode

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.

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

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

function logMessage(message: string): void {
  console.log(message);
}
logMessage("This is a message."); // Output: This is a message.
Enter fullscreen mode Exit fullscreen mode

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.

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

A function that never returns (infinite loop):

function infiniteLoop(): never {
  while (true) {}
}
Enter fullscreen mode Exit fullscreen mode

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.

type Point = { x: number, y: number };
let myPoint: Point = { x: 10, y: 20 };
console.log(myPoint); // Output: { x: 10, y: 20 }
Enter fullscreen mode Exit fullscreen mode

Using a type alias for union types:

type ID = number | string;
let userId: ID = 101;
let anotherId: ID = "user101";
console.log(userId); // Output: 101
console.log(anotherId); // Output: user101
Enter fullscreen mode Exit fullscreen mode

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.

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

Combining type aliases with objects:

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.
Enter fullscreen mode Exit fullscreen mode

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 Portfolio

Top comments (9)

Collapse
 
mcubico profile image
Mauricio Montoya Medrano

Muchas gracias por compartir, excelente contenido

Collapse
 
nahidulislam profile image
Nahidul Fahim

Thank you so much.

Collapse
 
eduard_iliasenco_6d20f857 profile image
Eduard Iliasenco

You missed any and unknown

Collapse
 
nahidulislam profile image
Nahidul Fahim

Yes. Thank you for your suggestion. I'll post about the missing data types in another article. πŸ™‚ It's great to hear from you.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

So TypeScript doesn't have Symbol or BigInt? πŸ€”

Collapse
 
nahidulislam profile image
Nahidul Fahim

Obviously the post doesn't cover all the topics or data types of TypeScript. It covers the most used data types that we often need. 😊

Collapse
 
natucode profile image
natucode

No, but I you want, you can create your own 😊

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

I just checked with the TypeScript playground. TS does indeed have BigInt and Symbol - so it looks like the post author missed them.

Collapse
 
suleman_7 profile image
suleman15

Its really help thanks for this post. I like it