TypeScript has become one of the most popular languages for frontend and backend development. It extends JavaScript by adding static typing, making your code more predictable, maintainable, and bug-free.
In this blog, we’ll walk through basic TypeScript concepts with examples, including type annotations, functions, and the special unknown type.
Why Learn TypeScript?
Before diving into examples, here’s why developers love TypeScript:
- Type Safety – Prevents bugs by catching errors at compile time.
- Better Code Completion – Works perfectly with IDEs like VS Code.
- Easier Collaboration – Teams can understand data structures faster.
- Scalable Applications – Great for large projects where maintainability matters.
Example: Function with Type Annotations
Let’s start with a simple example. Imagine you’re building an e-commerce app where you need to calculate the total price after applying a discount.
function getTotal(
unitPrice: number,
quantity: number,
discount: number
): number {
const priceWithoutDiscount = unitPrice * quantity;
const discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
// Example usage:
console.log(getTotal(100, 2, 0.1)); // Output: 180
Key Points:
- Each parameter (
unitPrice,quantity,discount) has a type annotation (number). - The function itself returns a
number. - If you try to pass a string instead of a number, TypeScript will throw an error.
Variables Without Type Annotations
TypeScript can infer types automatically, even if you don’t explicitly annotate them.
let price = 500; // inferred as number
let productName = "Laptop"; // inferred as string
- Here,
priceis automatically treated as anumber. productNameis automatically treated as astring.
⚡ Tip: Always use annotations in large projects for clarity, but inference works well for simple cases.
Using the unknown Type
The unknown type is a safer alternative to any. It means the variable could be anything, but you must check its type before using it.
let data: unknown;
data = 42;
data = "Hello TypeScript";
if (typeof data === "string") {
console.log(data.toUpperCase()); // Safe: TypeScript knows it's a string
}
Why use unknown?
- Unlike
any, it forces you to perform type checks before using the value. - Helps reduce runtime errors.
Real-World Use Case: API Responses
When working with APIs, you may not always know the exact shape of the response. Using unknown ensures you validate the response first:
function handleApiResponse(response: unknown) {
if (typeof response === "object" && response !== null) {
console.log("Valid response object:", response);
} else {
console.log("Unexpected response type");
}
}
Beginner-Friendly Tips for Learning TypeScript
- Start by converting small JavaScript files to TypeScript.
- Use
tsc --initto create a TypeScript project. - Enable
strictmode intsconfig.jsonfor best practices. - Practice with small utility functions like
getTotalbefore moving to bigger apps.
Common Interview Questions on TypeScript
Q1. What is the difference between any and unknown in TypeScript?
anylets you use the variable without restrictions (unsafe).unknownrequires type checking before usage (safe).
Q2. What is Type Inference in TypeScript?
TypeScript can automatically assign types to variables based on their initial values without explicit annotations.
Q3. Can you explain the benefits of using TypeScript over JavaScript?
- Compile-time error checking
- Improved tooling and autocompletion
- Scalability in large applications
Q4. How does TypeScript handle function return types?
You can specify return types explicitly, or TypeScript will infer them based on the function body.
Conclusion
TypeScript makes JavaScript development more reliable by introducing type safety and strong tooling support. We covered:
- Functions with type annotations
- Variables with and without annotations
- The
unknowntype with real-world usage
🚀 Keep practicing with small examples, and you’ll soon feel the power of TypeScript in larger projects.
