typescript vs javascript syntax differences: The discussion

What are the key syntax differences between TypeScript and JavaScript, and could you provide an illustrative example with an explanation?

TypeScript and JavaScript share many similarities, but TypeScript introduces additional syntax due to its static typing features. Here are some key syntax differences:

  1. Variable Declaration with Types:

    • JavaScript: Variables are declared without specifying types.
    javascript
    let variableName = 10;
    • TypeScript: Variable types can be explicitly defined.
    typescript
    let variableName: number = 10;
  2. Function Parameters and Return Types:

    • JavaScript: Function parameters and return types are not explicitly typed.
    javascript
    function add(a, b) {
    return a + b;
    }
    • TypeScript: Types for parameters and return values can be specified.
    typescript
    function add(a: number, b: number): number {
    return a + b;
    }
  3. Interfaces and Type Annotations:

    • JavaScript: No built-in support for interfaces.

    • TypeScript: Interfaces can be defined to enforce a specific structure.

    typescript
    interface Person {
    name: string;
    age: number;
    }

    function getPersonInfo(person: Person): string {
    return `Name: ${person.name}, Age: ${person.age}`;
    }
  4. Enum:

    • JavaScript: Enums are not natively supported.

    • TypeScript: Enums can be used to define named constant values.

    typescript
    enum Direction {
    Up,
    Down,
    Left,
    Right
    }

    let userDirection: Direction = Direction.Up;

These examples highlight some of the syntax differences between TypeScript and JavaScript, showcasing how TypeScript introduces static typing and other features to enhance code maintainability and developer experience.

একটি মন্তব্য পোস্ট করুন

0 মন্তব্যসমূহ