TypeScript Basic Syntax
TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. It offers additional features such as static types, interfaces, and type annotations that help developers write more robust and maintainable code. This document covers the basic syntax of TypeScript.
Type Annotations
Type annotations allow you to explicitly specify the types of variables, function parameters, and return values.
let isDone: boolean = false;
let age: number = 25;
let name: string = "John";
Functions
TypeScript allows you to specify the types of function parameters and return values.
function add(a: number, b: number): number {
return a + b;
}
let result: number = add(5, 3);
Interfaces
Interfaces define the structure of an object. They can be used to enforce type checking on objects.
interface Person {
name: string;
age: number;
}
let user: Person = {
name: "Alice",
age: 30
};
Classes
TypeScript supports classes, which are a blueprint for creating objects. Classes can have properties and methods.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): void {
console.log(`${this.name} makes a noise.`);
}
}
let dog = new Animal("Dog");
dog.speak(); // Dog makes a noise.
Enums
Enums allow you to define a set of named constants.
enum Direction {
Up,
Down,
Left,
Right
}
let dir: Direction = Direction.Up;
Generics
Generics allow you to create reusable components that work with a variety of types.
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("Hello");
Type Assertions
Type assertions allow you to override the inferred type of a variable.
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Modules
Modules allow you to organize your code into separate files and namespaces.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
// main.ts
import { add } from './math';
let result = add(2, 3);
Conclusion
These are some of the basic syntax features of TypeScript. By using type annotations, interfaces, classes, enums, generics, type assertions, and modules, you can write more robust and maintainable code. For more advanced features and configurations, refer to the TypeScript documentation (opens in a new tab).