No, browsers can't directly run TypeScript. It needs to be converted to JavaScript first. You can use:
For instance, if you have a myFile.ts file, you can use the TypeScript Compiler with the command:
$ tsc myFile.ts
This command generates a file named myFile.js.
To include myFile.js in your HTML, you can write the following code:
<!DOCTYPE html>
<html>
<head>
<title>TypeScript Example</title>
</head>
<body>
<script src="myFile.js"></script>
</body>
</html>
Open the HTML file in your browser, and the JavaScript compiled from myFile.ts will run just like any other JavaScript code.
TypeScript is like JavaScript with superpowers. It helps programmers write better code with fewer mistakes. While it requires an extra step before running in browsers, many developers find the benefits worth it, especially for bigger or more complex projects.
Some examples demonstrate how TypeScript can catch errors early, provide better code suggestions, and make your code more self-documenting.
JavaScript:
function addNumbers(a, b) {
return a + b;
}
console.log(addNumbers("5", 10)); // Outputs "510" (string concatenation)
TypeScript:
function addNumbers(a: number, b: number): number {
return a + b;
}
console.log(addNumbers("5", 10)); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
JavaScript:
let person = {
name: "John",
age: 30
};
person.adress; // No error, but 'adress' is misspelled and doesn't exist
TypeScript:
interface Person {
name: string;
age: number;
}
let person: Person = {
name: "John",
age: 30
};
person.adress; // Error: Property 'adress' does not exist on type 'Person'.
JavaScript:
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
}
let myCar = new Car("Toyota", "Corolla");
console.log(myCar.year); // Undefined, no error
TypeScript:
class Car {
make: string;
model: string;
constructor(make: string, model: string) {
this.make = make;
this.model = model;
}
}
let myCar = new Car("Toyota", "Corolla");
console.log(myCar.year); // Error: Property 'year' does not exist on type 'Car'.
For more information, visit https://www.typescriptlang.org/docs/