Technology Encyclopedia Home >How is TypeScript different from JavaScript?

How is TypeScript different from JavaScript?

TypeScript is a superset of JavaScript that adds optional static typing and other features to the language. It is designed to help developers catch errors early through type checking and to provide better tooling support, such as autocompletion and refactoring.

Key differences include:

  1. Type System: TypeScript allows developers to define types for variables, function parameters, and return values, which can help catch type-related errors at compile time rather than at runtime. For example, in TypeScript, you can declare a variable with a specific type like let name: string = "Alice";, whereas in JavaScript, all variables are dynamically typed.

  2. Interfaces and Classes: TypeScript supports interfaces and classes, which can be used to define the structure of objects and enforce certain contracts. This is not available in JavaScript, which only has prototypes.

  3. Decorators: TypeScript introduces decorators, which are a way to add metadata to classes, methods, or properties. This can be useful for frameworks like Angular.

  4. Transpilation: TypeScript code is transpiled (compiled) into plain JavaScript, which means it can run in any environment that supports JavaScript. This is similar to how CoffeeScript or JSX is compiled into JavaScript.

  5. Modern JavaScript Features: TypeScript often includes features from future JavaScript standards, allowing developers to use them before they are widely supported in all browsers.

For example, consider a simple function in JavaScript:

function greet(name) {
    return "Hello, " + name;
}

In TypeScript, you might write:

function greet(name: string): string {
    return "Hello, " + name;
}

Here, name is explicitly typed as a string, and the function is declared to return a string. If you try to pass a non-string value to greet, TypeScript will give you a compile-time error.

For cloud-related development, TypeScript is often used in conjunction with frameworks like Angular, which is supported by Tencent Cloud's Web Application Firewall (WAF) and Cloud Functions services, providing a robust environment for deploying and managing TypeScript-based applications.