JavaScript:
var x = 10;
TypeScript:
let x: number = 10;
In TypeScript, we need to specify the data type of a variable explicitly. JavaScript does not require this.
JavaScript:
function greet(name) {
console.log("Hello, " + name + "!");
}
TypeScript:
function greet(name: string): void {
console.log("Hello, " + name + "!");
}
In TypeScript, we need to specify the data type of the function parameters and the return type of the function. JavaScript does not require this.
JavaScript:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + " makes a noise.");
}
}
TypeScript:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): void {
console.log(this.name + " makes a noise.");
}
}
In TypeScript, we need to specify the data type of the class properties and the return type of the class methods. JavaScript does not require this.
JavaScript:
// This is a comment
var x = 10; // This is also a comment
TypeScript:
// This is a comment
let x: number = 10; // This is also a comment
In TypeScript, we can annotate the types of variables, functions, and class properties with comments or with explicit type annotations. JavaScript does not support type annotations.
JavaScript:
function greet(name, message) {
message = message || "Hello";
console.log(message + ", " + name + "!");
}
TypeScript:
function greet(name: string, message?: string): void {
message = message || "Hello";
console.log(message + ", " + name + "!");
}
In TypeScript, we can make a function parameter optional by using the ? symbol. JavaScript does not support this.