This repository contains a list of TypeScript concepts, examples. It is a guide for beginners to learn TypeScript.
- Introduction
- Installation
- Basic Types
- Variable Declarations
- Interfaces
- Classes
- Functions
- Generics
- Enums
- Type Inference
- Type Compatibility
- Advanced Types
- Symbols
- Iterators and Generators
- Modules
- Namespaces
- Namespaces and Modules
- Module Resolution
- Declaration Merging
- JSX
- Decorators
- Mixins
- Triple-Slash Directives
- Type Checking JavaScript Files
- Utility Types
TypeScript is a superset of JavaScript that adds optional types to the language. It is a statically typed language that compiles to plain JavaScript. TypeScript is developed and maintained by Microsoft.
TypeScript is designed for the development of large applications and transcompiles to JavaScript. As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript programs.
To install TypeScript, you need to have Node.js installed on your system. You can install TypeScript using npm, the Node.js package manager.
npm install -g typescript
To check the version of TypeScript installed, run the following command:
tsc -v
TypeScript supports the following basic types:
number
: All numeric values are represented using thenumber
type. TypeScript supports both decimal and hexadecimal literals.string
: Thestring
type is used to represent textual data.boolean
: Theboolean
type is used to represent a logical value. It can have two values:true
andfalse
.null
: Thenull
type is used to represent an intentional absence of an object value.undefined
: Theundefined
type is used to represent a variable that has not been assigned a value.void
: Thevoid
type is used on function return types to represent a function that does not return a value.any
: Theany
type is used to represent a value of any type. It is used when the type of the variable is not known at compile time.never
: Thenever
type is used to represent the type of values that never occur. For example, a function that throws an error or never returns.
let num: number = 10;
let str: string = 'Hello, TypeScript';
let isValid: boolean = true;
let n: null = null;
let u: undefined = undefined;
let v: void = undefined;
let a: any = 10;
let nvr: never = (() => {
throw new Error('An error occurred');
})();
TypeScript supports the following variable declarations:
var
: Thevar
keyword is used to declare a variable. The scope of a variable declared usingvar
is the function in which it is declared.let
: Thelet
keyword is used to declare a block-scoped variable. The scope of a variable declared usinglet
is the block in which it is declared.const
: Theconst
keyword is used to declare a block-scoped variable that cannot be reassigned. The value of a variable declared usingconst
cannot be changed.
var a = 10;
let b = 20;
const c = 30;
An interface in TypeScript is a way to define a contract in your code. It defines the syntax for classes to follow. Interfaces are used to define the structure of an object.
interface Person {
name: string;
age: number;
}
let person: Person = {
name: 'John Doe',
age: 30,
};
Classes in TypeScript are used to create objects. A class is a blueprint for creating objects. It encapsulates data for the object and methods to manipulate the data.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
let person = new Person('John Doe', 30);
console.log(person.greet());
Functions in TypeScript are used to define a block of code that can be called and executed later. Functions can take parameters and return values.
function add(a: number, b: number): number {
return a + b;
}
let sum = add(10, 20);
console.log(sum);
Generics in TypeScript allow you to create reusable components. They enable you to write functions, classes, and interfaces that work with any data type.
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>('Hello, TypeScript');
console.log(output);
Enums in TypeScript are used to define a set of named constants. They make it easier to document intent or create a set of distinct cases.
enum Direction {
Up = 1,
Down,
Left,
Right,
}
let direction: Direction = Direction.Up;
console.log(direction);
TypeScript has a feature called type inference. It allows you to omit the type annotations in your code. TypeScript automatically infers the type based on the value assigned to the variable.
let num = 10;
let str = 'Hello, TypeScript';
let isValid = true;
TypeScript uses a structural type system. Type compatibility in TypeScript is based on the shape that values have. If the shape of an object is the same, then the types are compatible.
interface Person {
name: string;
age: number;
}
let person: Person = {
name: 'John Doe',
age: 30,
};
let anotherPerson = person;
console.log(anotherPerson);
TypeScript supports the following advanced types:
- Union Types
- Intersection Types
- Type Guards
- Type Aliases
- Type Assertions
- Literal Types
- Index Types
- Mapped Types
- Conditional Types
type StringOrNumber = string | number;
let value: StringOrNumber = 'Hello, TypeScript';
value = 10;
console.log(value);
Symbols in TypeScript are a new primitive data type. They are used to create unique identifiers for object properties.
let sym1 = Symbol('key');
let sym2 = Symbol('key');
console.log(sym1 === sym2); // false
Iterators and generators are a feature of TypeScript that allows you to define custom iteration behavior.
let numbers = [1, 2, 3];
let iterator = numbers[Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
Modules in TypeScript are used to organize code. They allow you to split your code into multiple files. Each file is a module that can export and import code.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
// app.ts
import { add } from './math';
let sum = add(10, 20);
console.log(sum);
Namespaces in TypeScript are used to organize code. They allow you to group related code together. Namespaces are a way to create a global object that contains other objects.
namespace Math {
export function add(a: number, b: number): number {
return a + b;
}
}
let sum = Math.add(10, 20);
console.log(sum);
Namespaces and modules are two ways to organize code in TypeScript. Namespaces are used to group related code together, while modules are used to split your code into multiple files.
// math.ts
export namespace Math {
export function add(a: number, b: number): number {
return a + b;
}
}
// app.ts
import { Math } from './math';
let sum = Math.add(10, 20);
console.log(sum);
Module resolution in TypeScript is the process of finding and loading modules. TypeScript supports several module resolution strategies.
import { add } from './math';
Declaration merging in TypeScript is a feature that allows you to extend the definition of an existing type. It is used to combine multiple declarations into a single definition.
interface Person {
name: string;
}
interface Person {
age: number;
}
let person: Person = {
name: 'John Doe',
age: 30,
};
console.log(person);
JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. TypeScript supports JSX out of the box.
let element = <h1>Hello, TypeScript</h1>;
console.log(element);
Decorators in TypeScript are a way to add metadata to classes, methods, and properties. They are a feature of TypeScript that allows you to extend the behavior of a class without modifying its code.
function log(target: any, key: string) {
console.log(`${key} was called`);
}
class Calculator {
@log
add(a: number, b: number): number {
return a + b;
}
}
let calc = new Calculator();
calc.add(10, 20);
Mixins in TypeScript are a way to add methods and properties from one class to another class. They are a way to extend the functionality of a class without using inheritance.
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
interface Loggable {
log(): void;
}
function LoggableMixin<T extends new (...args: any[]) => any>(Base: T) {
return class extends Base implements Loggable {
log() {
console.log(this.name);
}
};
}
const LoggablePerson = LoggableMixin(Person);
let person = new LoggablePerson('John Doe');
person.log();
Triple-slash directives in TypeScript are used to declare dependencies between files. They are a way to reference other files in your TypeScript code.
/// <reference path="math.ts" />
let sum = Math.add(10, 20);
console.log(sum);
TypeScript can be used to type-check JavaScript files. You can use JSDoc comments to add type annotations to your JavaScript code.
/**
* @param {number} a
* @param {number} b
* @returns {number}
*/
function add(a, b) {
return a + b;
}
let sum = add(10, 20);
console.log(sum);
TypeScript provides a set of utility types that can be used to manipulate and transform types. These utility types are predefined in TypeScript and can be used to create new types.
type Person = {
name: string;
age: number;
};
type ReadonlyPerson = Readonly<Person>;
let person: ReadonlyPerson = {
name: 'John Doe',
age: 30,
};
person.name = 'Jane Doe'; // Error: Cannot assign to 'name' because it is a read-only property
This project is licensed under the MIT License - see the LICENSE file for details.
If you like this learning repository and find it useful, consider buying me a coffee or sponsoring me through the GitHub Sponsor. Your support will help me to continue and bring more exciting projects. Thank you!
Show your support by 🌟 the repository.