TypeScript is a superset of JavaScript, adding static typing and other features to the language. This article explores the syntactical differences between TypeScript and JavaScript, covering various aspects from variable declarations to advanced type annotations.
Variable Declarations
In JavaScript, variable declarations are straightforward and can be dynamically typed.
let x = 5; // Dynamic typing
const PI = 3.14; // Constants
var y = 'Hello'; // Legacy variable declaration
TypeScript introduces static typing using the let
, const
, and var
keywords.
let x: number = 5; // Static typing
const PI: number = 3.14; // Constants
var y: string = 'Hello'; // Legacy variable declaration
Function Declarations
Function parameters and return types are not explicitly defined in JavaScript.
function add(a, b) {
return a + b;
}
In TypeScript, you can specify parameter types and return types.
function add(a: number, b: number): number {
return a + b;
}
Object Oriented Programming
JavaScript supports object-oriented programming using prototypes.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
console.log(`Hello, ${this.name}!`);
};
const john = new Person('John');
john.greet();
TypeScript enhances object-oriented features with classes and interfaces.
class Person {
constructor(public name: string) {}
greet(): void {
console.log(`Hello, ${this.name}!`);
}
}
const john = new Person('John');
john.greet();
Type Annotations/Inference
JavaScript is dynamically typed, and variable types are inferred at runtime.
let dynamicVar = 5; // Dynamic typing
TypeScript allows explicit type annotations.
let explicitVar: number = 5; // Static typing
Modules
JavaScript uses the import
and export
syntax for module management in modern applications.
// Exporting
export const PI = 3.14;
// Importing
import { PI } from './math';
TypeScript supports the same module syntax and adds support for a tsconfig.json
file for configuration.
// Exporting
export const PI: number = 3.14;
// Importing
import { PI } from './math';
Advanced Types
TypeScript introduces advanced type features like interfaces, unions, and generics.
interface Point {
x: number;
y: number;
}
type Shape = 'circle' | 'square'; //union
function identity<T>(arg: T): T {
//generics
return arg;
}
Conclusion
While JavaScript and TypeScript share many similarities, TypeScript extends JavaScript by introducing static typing and additional features, making it a powerful choice for large-scale applications where type safety and advanced tooling are crucial. Developers can choose the right language based on the requirements of their projects.