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!"
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!
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
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"]
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 }
Using an interface:
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.
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
:
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.
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:
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.
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):
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.
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:
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.
type Greeting = (name: string) => string;
const sayHello: Greeting = (name) => `Hello, ${name}!`;
console.log(sayHello("Bob")); // Output: Hello, Bob!
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.
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.
Drop me an email here: nahidul7562@gmail.com
Follow me on: 🙋🏻♂️
Explore my portfolio
Welcome to my professional portfolio website—a curated glimpse into my professional world. Here, you'll find:
🌟 A collection of standout projects highlighting my expertise
🚀 Insights into my career trajectory and key achievements
💼 A showcase of my diverse skills and competencies
Whether you're seeking inspiration, exploring collaboration opportunities, or simply curious about my work, I invite you to peruse my portfolio.
Your visit could be the first step towards a valuable professional connection. 🤝 Thank you for your interest—I look forward to the possibilities our interaction might bring. 😊
Top comments (9)
Muchas gracias por compartir, excelente contenido
Thank you so much.
You missed any and unknown
Yes. Thank you for your suggestion. I'll post about the missing data types in another article. 🙂 It's great to hear from you.
So TypeScript doesn't have
Symbol
orBigInt
? 🤔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. 😊
No, but I you want, you can create your own 😊
I just checked with the TypeScript playground. TS does indeed have
BigInt
andSymbol
- so it looks like the post author missed them.Its really help thanks for this post. I like it