What is TypeScript? The Powerhouse Superset

What is TypeScript? The Powerhouse Superset
Photo by Nangialai Stoman / Unsplash

TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. It is designed for the development of large applications and transcompiles to JavaScript, allowing it to run anywhere JavaScript runs. TypeScript helps developers write more maintainable and scalable code by adding strong typing, interfaces, and other modern features to JavaScript.

What is TypeScript?

TypeScriptis an open-source language developed by Microsoft. It builds on JavaScript by adding static types, enabling developers to catch errors early in the development process, making applications more robust and easier to debug. TypeScript's type system allows developers to define variable types, function return types, and object shapes, which improves code clarity and predictability.


In case you missed our first article of our learning series, we recommend that you take a look at What is JavaScript? The Most In-Demand For Web Developers for an easy reference.

Basic TypeScript Sample

Here's a simple TypeScript example that defines a function to greet a user:

function greet(name: string): string {
    return `Hello, ${name}!`;
}

let user: string = "Jane User";
`console.log(greet(user)); 

In this example, the name parameter is explicitly typed as string, and the function is defined to return a string.

TypeScript for Scalability and Maintainability

TypeScript is particularly beneficial for large-scale projects where maintainability and scalability are critical. It introduces several features that help manage complex codebases:

  • Static Typing: Types are checked at compile-time, reducing runtime errors.
  • Interfaces: Define contracts within your code, improving code structure and reusability.
  • Namespaces and Modules: Organize code into logical groups, making it easier to navigate and manage.
  • Advanced IDE Support: Editors like Visual Studio Code provide robust support for TypeScript, including autocomplete, type checking, and refactoring tools.

TypeScript Interface

interface User {
    name: string;
    age: number;
}

function printUser(user: User): void {
    console.log(`Name: ${user.name}, Age: ${user.age}`);
}

const user: User = { name: "John Doe", age: 30 };
printUser(user);

In this example, the User interface defines the structure of a user object, ensuring that any object passed to the printUser function adheres to this structure.

TypeScript with Node.js

TypeScript can be used with Node.js to build server-side applications, providing the benefits of static typing to backend development. NodeJS, a JavaScript runtime built on Chrome's V8 JavaScript engine, is well-suited for high-throughput and low-latency applications due to its non-blocking, event-driven architecture.

Node.js with TypeScript Example

Here's a basic NodeJS server written in TypeScript:

import * as http from 'http';

const hostname: string = '127.0.0.1';
const port: number = 3000;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello, World!\n');
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

This example sets up an HTTP server that responds with Hello, World! to any request.

TypeScript Tooling

TypeScript comes with a rich set of tools to enhance the development experience:

  • TypeScript Compiler (TSC): Transcompiles TypeScript code to JavaScript.
  • ts-node: Runs TypeScript files directly, enabling faster development and testing.
  • TSLint and ESLint: Linting tools to ensure code quality and adherence to best practices.
  • TypeScript Playground: An online editor for experimenting with TypeScript code.

TypeScript Configuration

TypeScript projects are configured using a tsconfig.json file, which specifies the compiler options and files to be included. Here’s a basic tsconfig.json:

{
    "compilerOptions": {
        "target": "ES6",
        "module": "commonjs",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true
    },
    "include": ["src"]
}

The Advantages of TypeScript

TypeScript offers several key advantages over JavaScript:

  • Early Error Detection: Catch errors at compile-time rather than runtime.
  • Improved Code Readability and Maintainability: Types and interfaces make the code self-documenting and easier to understand.
  • Enhanced IDE Support: Better autocomplete, navigation, and refactoring capabilities.
  • Large Ecosystem and Community: Strong community support and a rich ecosystem of libraries and frameworks.

TypeScript Libraries and Frameworks

TypeScript integrates seamlessly with popular JavaScript libraries and frameworks. Here are a few examples:

  • React: TypeScript enhances React development with strong typing for props, state, and component methods.
  • Angular: Built with TypeScript, Angular leverages its features for robust application development.
  • Node.js: TypeScript can be used to build scalable and maintainable server-side applications.

React with TypeScript

import React, { useState } from 'react';

interface CounterProps {
    initialCount: number;
}

const Counter: React.FC<CounterProps> = ({ initialCount }) => {
    const [count, setCount] = useState(initialCount);

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
    );
};

export default Counter;

In this example, the Counter component uses TypeScript to define the type of its props.

Learning TypeScript

To get started with TypeScript, there are numerous resources available:

  • Official TypeScript Documentation: Comprehensive guide and API reference.
  • TypeScript Deep Dive: An open-source book by Basarat Ali Syed.
  • TypeScript for JavaScript Programmers: A guide to transitioning from JavaScript to TypeScript.

A Good Learning Path

  1. Introduction to TypeScript: Understand the basics of TypeScript syntax and features.
  2. TypeScript with React: Learn how to use TypeScript in a React application.
  3. Advanced TypeScript Concepts: Dive deeper into advanced topics like generics, decorators, and module resolution.

The Conclusion

TypeScriptis a powerful tool for modern web development, offering robust typing and advanced features that enhance the capabilities of JavaScript. By adopting TypeScript, developers can create more reliable, scalable, and maintainable applications. Whether you’re building client-side applications with frameworks like React and Angular, or server-side applications with NodeJS, TypeScript provides the tools and features to streamline your development process and improve code quality.


Do you like what you're reading from the CoderOasis Technology Blog? We recommend reading our Implementing RSA in Python from Scratch series next.

The CoderOasis Community

Did you know we have a Community Forums and Discord Server? which we invite everyone to join us? Want to discuss this article with other members of our community? Want to join a laid back place to chill and discuss topics like programming, cybersecurity, web development, and Linux? Consider joining us today!