TypeScript
Variables
In TypeScript, variables can be declared using the let or const keywords. Additionally, variables can be explicitly typed using the : Type syntax. Here's an example:
let message: string = "Hello, TypeScript!";
const pi: number = 3.14;
TypeScript provides type inference, allowing variables to have their types inferred by the compiler based on their initial values. This feature enables writing cleaner code without explicit type annotations. For more details on variables in TypeScript, refer to the TypeScript documentation on variables.
Functions
In TypeScript, functions can be declared using the function keyword. Function parameters can be explicitly typed using the : Type syntax, and the return type can also be specified using the : ReturnType syntax. Here's an example:
function add(x: number, y: number): number { return x + y;}
In the above example, the function named "add" takes two parameters, "x" and "y", both of type number. It specifies the return type as number. The function body performs the addition of "x" and "y" and returns the result.
TypeScript supports optional parameters, default parameter values, and rest parameters in functions, providing flexibility in function declarations. For more details on functions in TypeScript, refer to the TypeScript documentation on functions.
Interfaces
In TypeScript, interfaces can be declared using the interface keyword. Interfaces are used to define the structure of objects, functions, classes, and arrays. Here's an example:
interface Person { name: string; age: number;}
In the above example, the interface named "Person" defines the structure of an object. It specifies that an object of type Person must have a name property of type string and an age property of type number.
Classes
In TypeScript, classes can be declared using the class keyword. Classes are used to define the structure of objects, functions, and arrays. Here's an example:
class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; }}
In the above example, the class named "Person" defines the structure of an object. It specifies that an object of type Person must have a name property of type string and an age property of type number. It also specifies a constructor function that takes a name parameter of type string and an age parameter of type number.
Enums
In TypeScript, enums can be declared using the enum keyword. Enums are used to define a set of named constants. Here's an example:
enum Color { Red, Green, Blue}
In the above example, the enum named "Color" defines a set of named constants. It specifies that the constants Red, Green, and Blue are of type Color.