Typescript syntax
Created By: chatGPT
TypeScript is a superset of JavaScript that adds static typing to the language. By integrating TypeScript into your JavaScript project, you not only enhance the development experience but also reduce runtime errors. Below are some basic syntax features of TypeScript.
// Basic Type Annotations
let isFinished: boolean = true;
let score: number = 95;
let username: string = 'JohnDoe';
// Array Type Annotations
let scores: number[] = [95, 82, 90];
let names: Array<string> = ['Alice', 'Bob'];
// Tuples
let user: [number, string] = [1, 'Alice'];
// Any Type
let randomValue: any = 10;
randomValue = 'Now I am a string!';
TypeScript also supports interfaces which define the structure of an object. This enhances type safety and code readability.
// Defining an Interface
interface User {
id: number;
username: string;
isActive: boolean;
}
// Implementing an Interface
let user: User = {
id: 1,
username: 'Alice',
isActive: true
};
Functions in TypeScript can have typed parameters as well as a return type, making it clear what type of values will be passed and returned.
// Function with Typed Parameters and Return Type
function add(a: number, b: number): number {
return a + b;
}
let sum: number = add(5, 10);
TypeScript introduces enums which is a special data type that represents a set of named constants. They are useful for defining a set of related values.
// Defining an Enum
enum Color {
Red,
Green,
Blue
}
let myColor: Color = Color.Green;
Lastly, TypeScript supports classes and inheritance, bringing object-oriented programming features to JavaScript.
// Creating a Class
class Animal {
constructor(public name: string) {}
move(distanceInMeters: number): void {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Dog extends Animal {
bark(): void {
console.log('Woof!');
}
}
let dog = new Dog('Rex');
dog.move(10);
dog.bark();