chore: sync content to repo (#9691)

Co-authored-by: kamranahmedse <4921183+kamranahmedse@users.noreply.github.com>
This commit is contained in:
github-actions[bot]
2026-03-05 12:14:17 +01:00
committed by GitHub
parent afb2e53715
commit 88337e084e
93 changed files with 330 additions and 1605 deletions

View File

@@ -1,23 +1,7 @@
# Abstract Classes
Abstract classes in TypeScript are classes that cannot be instantiated on their own and must be subclassed by other classes. Abstract classes provide a blueprint for other classes and can have abstract methods, which are methods without a body and must be overridden by the subclass. These classes are useful for defining a common interface or basic functionality that other classes can inherit and build upon.
An abstract class is a class that cannot be instantiated directly. Its primary purpose is to define a blueprint for other classes. It can contain abstract methods (methods without implementation) and concrete methods (methods with implementation). Subclasses must provide concrete implementations for all abstract methods inherited from the abstract class, unless the subclass is also declared abstract. This ensures that subclasses adhere to a specific interface or contract.
```typescript
abstract class Animal {
abstract makeSound(): void;
Visit the following resources to learn more:
move(): void {
console.log('moving...');
}
}
class Dog extends Animal {
makeSound(): void {
console.log('bark');
}
}
```
Learn more from the following resources:
- [@official@Abstract Classes](https://www.typescriptlang.org/docs/handbook/2/classes.html#abstract-classes-and-members)
- [@official@Abstract Classes](https://www.typescriptlang.org/docs/handbook/2/classes.html#abstract-classes-and-members)

View File

@@ -1,13 +1,7 @@
# Access Modifiers
In TypeScript, access modifiers are keywords used to control the visibility and accessibility of class properties and methods. There are three access modifiers in TypeScript:
Access modifiers in object-oriented programming control the visibility of class members (properties and methods). They determine which parts of your code, or even external code, can access and modify those members. Common access modifiers include `public`, `private`, and `protected`, each offering different levels of accessibility and encapsulation.
- `public:` This is the default access modifier. Properties and methods declared as public can be accessed from anywhere, both inside and outside the class.
- `private:` Properties and methods declared as private can only be accessed within the same class. They are not accessible from outside the class.
- `protected:` Properties and methods declared as protected can be accessed within the class and its subclasses. They are not accessible from outside the class and its subclasses.
Visit the following resources to learn more:
Access modifiers in TypeScript allow you to define the level of visibility and accessibility of properties and methods in your class, making your code more maintainable and secure.
Learn more from the following resources:
- [@official@TypeScript Access Modifiers](https://www.typescripttutorial.net/typescript-tutorial/typescript-access-modifiers/)
- [@official@TypeScript Access Modifiers](https://www.typescripttutorial.net/typescript-tutorial/typescript-access-modifiers/)

View File

@@ -1,18 +1,8 @@
# Advanced Types
Advanced types in TypeScript are a set of advanced type constructs that allow for more complex and expressive type systems. Some of the most commonly used advanced types in TypeScript include:
TypeScript's advanced types allow for more precise and flexible type definitions beyond basic primitives. Intersection types combine multiple types into one, requiring a value to satisfy all combined types. Union types allow a value to be one of several specified types. Type aliases create a name for a type, making complex type definitions easier to reuse. Conditional types allow types to be determined based on a condition, often using generics. Index types enable you to extract the type of a property from another type using a key. Mapped types transform each property in a type, creating a new type based on the original. Type guards are functions that narrow down the type of a variable within a specific scope.
- Intersection Types
- Union Types
- Type Aliases
- Conditional Types
- Index Types
- Mapped Types
- Type Guards
These advanced types allow for more complex and expressive type systems, and enable you to write code that is safer, more maintainable, and easier to understand. By leveraging these advanced types, you can write code that is more robust, less prone to errors, and easier to maintain.
Learn more from the following links:
Visit the following resources to learn more:
- [@official@Advanced Topics](https://www.typescriptlang.org/docs/handbook/type-compatibility.html#advanced-topics)
- [@video@Tutorial of Typescript - Advanced Types](https://www.youtube.com/playlist?list=PLw5h0DiJ-9PBIgIyd2ZA1CVnJf0BLFJg2)
- [@video@Tutorial of Typescript - Advanced Types](https://www.youtube.com/playlist?list=PLw5h0DiJ-9PBIgIyd2ZA1CVnJf0BLFJg2)

View File

@@ -1,22 +1,7 @@
# Ambient Modules
Ambient modules in TypeScript are used to declare external modules or third-party libraries in a TypeScript program. Ambient modules provide type information for modules that have no TypeScript declarations, but are available in the global scope.
Ambient modules in TypeScript are used to describe the shape of existing JavaScript code when you don't have the TypeScript declaration files (`.d.ts`) readily available. They essentially allow you to tell the TypeScript compiler about the existence and structure of a JavaScript module, so you can import and use it in your TypeScript code without getting type errors, even if the module itself wasn't written in TypeScript.
Here's an example of how you can use ambient modules in TypeScript:
Visit the following resources to learn more:
```typescript
// myModule.d.ts
declare module 'my-module' {
export function doSomething(): void;
}
// main.ts
import * as myModule from 'my-module';
myModule.doSomething();
```
In this example, we declare an ambient module "my-module" in the `myModule.d.ts` file. This declaration provides type information for the "my-module" module, including the "doSomething" function that is exported from the module.
Learn more from the following links:
- [@official@Ambient Modules](https://www.typescriptlang.org/docs/handbook/modules/reference.html#ambient-modules)
- [@official@Ambient Modules](https://www.typescriptlang.org/docs/handbook/modules/reference.html#ambient-modules)

View File

@@ -4,18 +4,16 @@ TypeScript has a special type, `any`, that you can use whenever you dont want
When a value is of type `any`, you can access any properties of it (which will in turn be of type `any`), call it like a function, assign it to (or from) a value of any type, or pretty much anything else thats syntactically legal:
```typescript
let obj: any = { x: 0 };
// None of the following lines of code will throw compiler errors.
// Using `any` disables all further type checking, and it is assumed
// you know the environment better than TypeScript.
obj.foo();
obj();
obj.bar = 100;
obj = 'hello';
const n: number = obj;
```
let obj: any = { x: 0 };
// None of the following lines of code will throw compiler errors.
// Using `any` disables all further type checking, and it is assumed
// you know the environment better than TypeScript.
obj.foo();
obj();
obj.bar = 100;
obj = 'hello';
const n: number = obj;
Learn more from the following links:
Visit the following resources to learn more:
- [@official@any type in TypeScript](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any)
- [@official@any type in TypeScript](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any)

View File

@@ -1,11 +1,7 @@
# Array
To specify the type of an array like `[1, 2, 3]`, you can use the syntax `number[]`; this syntax works for any type (e.g. `string[]` is an array of strings, and so on). You may also see this written as `Array<number>`, which means the same thing.
An array is a data structure that stores an ordered collection of elements, where each element is accessed using its numerical index. Arrays are fundamental for managing lists of items, and in TypeScript, you define the types of elements that an array can hold, enforcing consistency and preventing errors. An array's length is mutable allowing you to dynamically add or remove elements.
```typescript
const numbers: number[] = [1, 2, 3];
```
Visit the following resources to learn more:
Learn more from the following links:
- [@official@Arrays](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#arrays)
- [@official@Arrays](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#arrays)

View File

@@ -4,14 +4,12 @@
For example:
```typescript
let anyValue: any = 42;
let anyValue: any = 42;
// we can assign any value to anyValue, regardless of its type
anyValue = 'Hello, world!';
anyValue = true;
// we can assign any value to anyValue, regardless of its type
anyValue = 'Hello, world!';
anyValue = true;
```
Visit the following resources to learn more:
Learn more from the following links:
- [@official@any](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any)
- [@official@any](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any)

View File

@@ -1,17 +1,7 @@
# As Const
# as const
`as const` is a type assertion in TypeScript that allows you to assert that an expression has a specific type, and that its value should be treated as a read-only value.
`as const` is a TypeScript feature that allows you to tell the compiler to infer the narrowest or most specific type possible for an expression. Instead of the compiler widening the type of a value to its general type (like inferring a string variable as `string`), `as const` makes the compiler infer the value as a constant type (like inferring a string variable as the specific string literal type `"hello"`). This is useful for creating immutable data structures or when you need the compiler to enforce the exact values allowed.
For example:
Visit the following resources to learn more:
```typescript
const colors = ['red', 'green', 'blue'] as const;
// colors is now of type readonly ['red', 'green', 'blue']
```
Using as const allows TypeScript to infer more accurate types for constants, which can lead to improved type checking and better type inference in your code.
Learn more from the following links:
- [@official@const assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions)
- [@official@const assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions)

View File

@@ -1,18 +1,7 @@
# As Type
# Type Assertions with `as`
In TypeScript, the as keyword is used for type assertions, allowing you to explicitly inform the compiler about the type of a value when it cannot be inferred automatically. Type assertions are a way to override the default static type-checking behavior and tell the compiler that you know more about the type of a particular expression than it does.
Type assertions in TypeScript are a way to tell the compiler the specific type of a variable. They allow you to override TypeScript's type inference when you know more about the type of a value than the compiler does. Using `as [type]` is one syntax for type assertions, allowing you to explicitly cast a variable to a more specific type. This doesn't perform any runtime type checking or conversion, it simply instructs the compiler to treat the variable as if it were of the specified type.
Here's a simple example:
Visit the following resources to learn more:
```typescript
let someValue: any = "Hello, TypeScript!";
let strLength: number = (someValue as string).length;
console.log(strLength); // Outputs: 18
```
In this example, someValue is initially of type any, and we use the as operator to assert that it is of type string before accessing its length property.
It's important to note that type assertions do not change the runtime type of a value, and do not cause any type of conversion. They are a compile-time construct used for static type checking in TypeScript.
- [@official@Type assertions](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions)
- [@official@Type assertions](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions)

View File

@@ -1,18 +1,7 @@
# Awaited
This type is meant to model operations like await in async functions, or the `.then()` method on Promises - specifically, the way that they recursively unwrap Promises.
`Awaited` is a utility type in TypeScript that is used to recursively unwrap the `Promise` type. It simulates the `await` operator's behavior in JavaScript. If you have a type that represents a `Promise`, `Awaited` can extract the underlying type that the `Promise` resolves to. It handles nested `Promise` types and other thenables, continually unwrapping until it reaches a non-promise type.
```typescript
type A = Awaited<Promise<string>>;
// type A = string
Visit the following resources to learn more:
type B = Awaited<Promise<Promise<number>>>;
// type B = number
type C = Awaited<boolean | Promise<number>>;
// type C = number | boolean
```
Learn more from the following links:
- [@official@Awaited`<Type>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#awaitedtype)
- [@official@Awaited<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#awaitedtype)

View File

@@ -1,12 +1,7 @@
# boolean
# Boolean Type in TypeScript
`boolean` is a primitive data type in TypeScript that represents a boolean value i.e. either true or false. Given below is an example of a boolean variable declaration:
A boolean type represents a logical value that can be either `true` or `false`. It is commonly used in programming to control the flow of execution based on certain conditions, allowing programs to make decisions and execute different code blocks depending on whether a condition is met. Boolean values are fundamental for expressing logical operations and comparisons.
```typescript
let isTrue: boolean = true;
let isFalse: boolean = false;
```
Visit the following resources to learn more:
Learn more from the following links:
- [@article@Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean)
- [@article@Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean)

View File

@@ -1,17 +1,11 @@
# Build Tools
Task runners automatically execute commands and carry out processes behind the scenes. This helps automate your workflow by performing mundane, repetitive tasks that you would otherwise waste an egregious amount of time repeating yourself.
Common usages of task runners include numerous development tasks such as: spinning up development servers, compiling code (ex. SCSS to CSS), running linters, serving files up from a local port on your computer, and many more!
Task runners automatically execute commands and carry out processes behind the scenes. This helps automate your workflow by performing mundane, repetitive tasks that you would otherwise waste an egregious amount of time repeating. Common usages of task runners include numerous development tasks such as: spinning up development servers, compiling code (ex. SCSS to CSS), running linters, serving files up from a local port on your computer, and many more!
Visit the following resources to learn more:
- [@article@webpack is a static module bundler for modern JavaScript applications](https://webpack.js.org/)
- [@article@Vite Next Generation Frontend Tooling](https://vitejs.dev)
- [@article@Parcel is a zero configuration build tool for the web](https://parceljs.org/)
- [@article@esbuild is an extremely fast JavaScript bundler and minifier](https://esbuild.github.io/)
- [@article@swc is a super-fast compiler written in Rust](https://swc.rs/)
- [@article@tsup is a zero-config TypeScript build tool](https://tsup.egoist.dev/)
- [@article@Rollup is a module bundler for JavaScript](https://rollupjs.org/guide/en/)
- [@article@tsdx is a zero-config CLI for TypeScript package development](https://tsdx.io/)
- [@feed@Explore top posts about Tools](https://app.daily.dev/tags/tools?ref=roadmapsh)
- [@official@webpack is a static module bundler for modern JavaScript applications](https://webpack.js.org/)
- [@official@Vite Next Generation Frontend Tooling](https://vitejs.dev)
- [@official@Parcel is a zero configuration build tool for the web](https://parceljs.org/)
- [@official@esbuild is an extremely fast JavaScript bundler and minifier](https://esbuild.github.io/)
- [@official@swc is a super-fast compiler written in Rust](https://swc.rs/)

View File

@@ -1,25 +1,7 @@
# Class
In TypeScript, a class is a blueprint for creating objects with specific properties and methods. Classes are a fundamental concept in object-oriented programming. Here is an example of a simple class in TypeScript:
A class is a blueprint for creating objects (instances) that share similar characteristics. It defines the properties (data) and methods (functions) that the objects will possess. Classes allow you to create reusable code structures by defining a template that you can then use to instantiate multiple objects with the same basic features.
```typescript
class Car {
make: string;
model: string;
year: number;
Visit the following resources to learn more:
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
drive() {
console.log(`Driving my ${this.year} ${this.make} ${this.model}`);
}
}
```
Learn more from the following links:
- [@official@TypeScript Classes](https://www.typescriptlang.org/docs/handbook/2/classes.html)
- [@official@TypeScript Classes](https://www.typescriptlang.org/docs/handbook/2/classes.html)

View File

@@ -1,27 +1,7 @@
# Classes
Classes in TypeScript are a blueprint for creating objects (instances of a class), providing a way to structure objects and encapsulate data and behavior. Classes in TypeScript have a similar syntax to classes in other object-oriented programming languages, such as Java and C#.
Classes are blueprints for creating objects, encapsulating data (properties) and behavior (methods) into a single unit. They provide a structured way to define the characteristics and actions that an object of that class can possess. This allows for creating multiple instances of the same object type with consistent properties and methods.
A class in TypeScript is defined using the class keyword, followed by the name of the class. The class definition can include fields (also known as properties or attributes), methods (functions), and a constructor.
Visit the following resources to learn more:
```typescript
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): void {
console.log(`${this.name} is making a sound`);
}
}
const dog = new Animal('Dog');
dog.makeSound(); // Output: Dog is making a sound
```
In this example, the `Animal` class has a name field, a constructor that sets the value of the `name` field, and a `makeSound` method. An instance of the `Animal` class can be created using the `new` keyword, and its methods and properties can be accessed using dot notation.
Learn more from the following resources:
- [@official@Tutorial - Classes](https://www.typescriptlang.org/docs/handbook/2/classes.html)
- [@official@Tutorial - Classes](https://www.typescriptlang.org/docs/handbook/2/classes.html)

View File

@@ -1,38 +1,10 @@
# Combining Types
In TypeScript, you can combine types using type union and type intersection.
Combining types in TypeScript allows you to create new, more complex types from existing ones. This is achieved through features like unions and intersections. A union type lets a variable hold values of different types, while an intersection type combines multiple types into a single type that has all the properties of each individual type. These mechanisms provide flexibility and expressiveness when defining the shape of your data.
## Type Union
The union operator `|` is used to combine two or more types into a single type that represents all the possible types. For example:
```typescript
type stringOrNumber = string | number;
let value: stringOrNumber = 'hello';
value = 42;
```
## Type Intersection
The intersection operator `&` is used to intersect two or more types into a single type that represents the properties of all the types. For example:
```typescript
interface A {
a: string;
}
interface B {
b: number;
}
type AB = A & B;
let value: AB = { a: 'hello', b: 42 };
```
Learn more from the following links:
Visit the following resources to learn more:
- [@official@Union Types in TypeScript](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types)
- [@article@Intersection Types in TypeScript](https://www.typescripttutorial.net/typescript-tutorial/typescript-intersection-types/)
- [@article@Type Aliases](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases)
- [@article@Keyof Type Operator](https://www.typescriptlang.org/docs/handbook/2/keyof-types.html#handbook-content)
- [@article@Keyof Type Operator](https://www.typescriptlang.org/docs/handbook/2/keyof-types.html#handbook-content)

View File

@@ -1,11 +1,7 @@
# Compiler Options
TypeScript compiler accepts a number of command line options that allow you to customize the compilation process. These options can be passed to the compiler using the `--` prefix, for example:
Compiler options in TypeScript provide fine-grained control over how the TypeScript compiler (`tsc`) transforms `.ts` files into JavaScript. These options are typically configured within a `tsconfig.json` file or passed directly via the command line. They dictate aspects like target ECMAScript version, module system, strictness of type checking, source map generation, and many other behaviors of the compilation process.
```bash
tsc --target ES5 --module commonjs
```
Visit the following resources to learn more:
Learn more from the following links:
- [@official@Compiler Options](https://www.typescriptlang.org/docs/handbook/compiler-options.html)
- [@official@Compiler Options](https://www.typescriptlang.org/docs/handbook/compiler-options.html)

View File

@@ -1,19 +1,8 @@
# Conditional Types
Conditional types in TypeScript are a way to select a type based on a condition. They allow you to write a type that dynamically chooses a type based on the types of its inputs. Conditional types are declared using a combination of the `infer` keyword and a type that tests a condition and selects a type based on the result of the test.
Conditional types in TypeScript allow you to define types that depend on other types, similar to a ternary operator in JavaScript. They enable you to express type relationships that change based on whether a specific type condition is met. This feature makes your type definitions more flexible and capable of handling complex scenarios where the resulting type depends on the structure or nature of another type.
For example, the following is a conditional type that takes two types and returns the type of the first argument if it extends the second argument, and the type of the second argument otherwise:
```typescript
type Extends<T, U> = T extends U ? T : U;
type A = Extends<string, any>; // type A is 'string'
type B = Extends<any, string>; // type B is 'string'
```
In this example, the Extends conditional type takes two types T and U and returns the type of the first argument `T` if it extends the second argument `U`, and the type of the second argument `U` otherwise. The T extends `U` syntax is used to test whether `T extends U`, and the `? T : U` syntax is used to select the type `T` if the test passes and the type `U` otherwise.
Learn more from the following links:
Visit the following resources to learn more:
- [@official@Conditional Types](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#handbook-content)
- [@video@Conditional Types - Advanced TypeScript](https://www.youtube.com/watch?v=QFWrbNehKk0)
- [@video@Conditional Types - Advanced TypeScript](https://www.youtube.com/watch?v=QFWrbNehKk0)

View File

@@ -1,20 +1,7 @@
# Constructor Overloading
In TypeScript, you can achieve constructor overloading by using multiple constructor definitions with different parameter lists in a single class. Given below is the example where we have multiple definitions for the constructor:
Constructor overloading allows a class to have multiple constructors with different parameter lists. This enables you to create objects of the class in different ways, providing flexibility in initialization based on the provided arguments. Each constructor variation handles the object's initialization differently depending on the types and number of arguments passed during instantiation.
```typescript
class Point {
// Overloads
constructor(x: number, y: string);
constructor(s: string);
constructor(xs: any, y?: any) {
// TBD
}
}
```
Visit the following resources to learn more:
Note that, similar to function overloading, we only have one implementation of the constructor and it's the only the signature that is overloaded.
Learn more from the following resources:
- [@official@Constructors - TypeScript](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors)
- [@official@Constructors - TypeScript](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors)

View File

@@ -1,15 +1,7 @@
# Constructor Params
# Constructor Parameters
In TypeScript, constructor parameters can be declared with access modifiers (e.g. `public`, `private`, `protected`) and/or type annotations. The parameters are then automatically assigned to properties of the same name within the constructor, and can be accessed within the class. For example:
In TypeScript classes, constructor parameters provide a concise way to define and initialize class properties directly within the constructor's parameter list. By using access modifiers like `public`, `private`, or `protected` before a constructor parameter, TypeScript automatically creates a corresponding class property with that name and assigns the constructor argument's value to it. This streamlines the process of property declaration and initialization, reducing boilerplate code.
```typescript
class Example {
constructor(private name: string, public age: number) {}
}
```
Visit the following resources to learn more:
In this example, the constructor has two parameters: name and age. name has a private access modifier, so it can only be accessed within the Example class. age has a public access modifier, so it can be accessed from outside the class as well.
Learn more from the following links:
- [@official@TypeScript - Construct](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors)
- [@official@TypeScript - Construct](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors)

View File

@@ -1,40 +1,7 @@
# Decorators
Decorators are a feature of TypeScript that allow you to modify the behavior of a class, property, method, or parameter. They are a way to add additional functionality to existing code, and they can be used for a wide range of tasks, including logging, performance optimization, and validation.
Decorators are a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. They use the form `@expression`, where `expression` must evaluate to a function that will be called at runtime with information about the decorated declaration. Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members. They essentially modify the behavior or functionality of the decorated code in a declarative way.
Here's an example of how you might use a decorator in TypeScript:
Visit the following resources to learn more:
```typescript
function log(
target: Object,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling ${propertyKey} with arguments: ${args}`);
return originalMethod.apply(this, args);
};
return descriptor;
}
class Calculator {
@log
add(a: number, b: number): number {
return a + b;
}
}
const calculator = new Calculator();
calculator.add(1, 2);
// Output: Calling add with arguments: 1,2
// Output: 3
```
In this example, we use the `@log` decorator to modify the behavior of the `add` method in the `Calculator` class. The `log` decorator logs the arguments passed to the method before calling the original method. This allows us to see what arguments are being passed to the method, without having to modify the method's code.
Learn more from the following links:
- [@official@Decorators](https://www.typescriptlang.org/docs/handbook/decorators.html#handbook-content)
- [@official@Decorators](https://www.typescriptlang.org/docs/handbook/decorators.html#handbook-content)

View File

@@ -1,3 +1,3 @@
# Ecosystem
# TypeScript Ecosystem
Have a look at the linked nodes for different tools and frameworks that you can use to build your projects.
The TypeScript ecosystem refers to the collection of tools, libraries, frameworks, and resources that support and enhance TypeScript development. It includes everything from build tools and linters to UI libraries and server-side frameworks that have TypeScript definitions available or are specifically designed to work well with TypeScript. The ecosystem also incorporates community resources like documentation, tutorials, and open-source projects that help developers learn and use TypeScript effectively.

View File

@@ -1,22 +1,7 @@
# Enum
Enums is not a type-level extension of JavaScript. It allows a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
An "enum" (short for enumeration) is a way to define a set of named constants. It provides a way to give more friendly names to sets of numeric values, making code more readable and maintainable. Enums allow you to define a type by enumerating its possible values, which can represent options, states, or any other set of distinct possibilities.
Here is an example of a numeric enum in TypeScript:
Visit the following resources to learn more:
```typescript
enum Direction {
Up = 1,
Down,
Left,
Right,
}
```
Above, we have a numeric enum where `Up` is initialized with `1`. All of the following members are auto-incremented from that point on. In other words, `Direction.Up` has the value `1`, `Down` has `2`, `Left` has `3`, and `Right` has `4`.
If we left off the initializer for `Up`, it would have the value `0` and the rest of the members would be auto-incremented from there.
Learn more from the following links:
- [@official@TypeScript - Enums](https://www.typescriptlang.org/docs/handbook/enums.html)
- [@official@TypeScript - Enums](https://www.typescriptlang.org/docs/handbook/enums.html)

View File

@@ -1,22 +1,7 @@
# Equality
# Equality in Type Guards and Narrowing
TypeScript also uses switch statements and equality checks like `===`, `!==`, `==`, and `!=` to narrow types. For example:
Equality in the context of type guards and narrowing refers to using comparison operators (like `===`, `!==`, `==`, `!=`) to refine the type of a variable within a TypeScript program. By comparing a variable against a specific value (or another variable), TypeScript can infer a more specific type for that variable within a certain scope, enabling safer and more accurate code execution by ruling out possibilities. This mechanism enhances type safety by allowing the compiler to understand the possible values and types a variable can hold at different points in the code.
```typescript
function example(x: string | number, y: string | boolean) {
if (x === y) {
// We can now call any 'string' method on 'x' or 'y'.
x.toUpperCase();
y.toLowerCase();
} else {
console.log(x);
console.log(y);
}
}
```
Visit the following resources to learn more:
When we checked that `x` and `y` are both equal in the above example, TypeScript knew their types also had to be equal. Since string is the only common type that both `x` and `y` could take on, TypeScript knows that `x` and `y` must be a string in the first branch.
Learn more from the following links:
- [@official@Equality Narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#equality-narrowing)
- [@official@Equality Narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#equality-narrowing)

View File

@@ -1,13 +1,7 @@
# Exclude
Exclude constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers.
`Exclude` is a utility type in TypeScript that constructs a new type by removing types from a union type. Given two types, `Type` and `ExcludedUnion`, `Exclude<Type, ExcludedUnion>` creates a type that includes all members of `Type` that are *not* assignable to `ExcludedUnion`. This is useful for filtering out specific types from a union, resulting in a more refined and specific type.
```typescript
type T0 = Exclude<'a' | 'b' | 'c', 'a'>; // "b" | "c"
type T1 = Exclude<'a' | 'b' | 'c', 'a' | 'b'>; // "c"
type T2 = Exclude<string | number | (() => void), Function>; // string | number
```
Visit the following resources to learn more:
Learn more from the following links:
- [@official@Exclude<UnionType, ExcludedMembers>](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers)
- [@official@Exclude<UnionType, ExcludedMembers>](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers)

View File

@@ -1,26 +1,7 @@
# Extending Interfaces
In TypeScript, you can extend an interface by creating a new interface that inherits from the original interface using the "extends" keyword. The new interface can include additional properties, methods, or redefine the members of the original interface.
Extending interfaces in TypeScript allows you to create new interfaces based on existing ones. This means a new interface can inherit all the properties and methods of a parent interface and add its own unique members, promoting code reuse and establishing a clear hierarchy of types. Think of it like inheritance in classes, but for interface definitions.
```typescript
interface Shape {
width: number;
height: number;
}
Visit the following resources to learn more:
interface Square extends Shape {
sideLength: number;
}
let square: Square = {
width: 10,
height: 10,
sideLength: 10,
};
```
In this example, the `Square` interface extends the `Shape` interface and adds an additional property `sideLength`. A variable of type `Square` must have all the properties defined in both `Shape` and `Square` interfaces.
Learn more from the following links:
- [@official@Extending Interfaces](https://www.typescriptlang.org/docs/handbook/2/objects.html)
- [@official@Extending Interfaces](https://www.typescriptlang.org/docs/handbook/2/objects.html)

View File

@@ -1,22 +1,7 @@
# External Modules
# External Modules in TypeScript
In TypeScript, external modules allow you to organize and share code across multiple files. External modules in TypeScript follow the CommonJS or ES modules standards.
External modules in TypeScript are files containing code that can be imported and used in other files. They help organize and structure your project by dividing code into logical units, improving maintainability and reusability. Each external module has its own scope, preventing naming conflicts and allowing you to explicitly control what is exposed from the module using `export` and what is consumed from other modules using `import`.
Here's an example of how you can use external modules in TypeScript:
Visit the following resources to learn more:
```typescript
// myModule.ts
export function doSomething() {
console.log('Doing something...');
}
// main.ts
import { doSomething } from './myModule';
doSomething(); // Output: "Doing something..."
```
In this example, we use the "export" keyword in the "myModule.ts" file to export the "doSomething" function, making it available for other files to use.
Learn more from the following links:
- [@article@TypeScript - External Module](https://learncodeweb.com/typescript/modules-in-typescript-explain-with-an-example/)
- [@article@TypeScript - External Module](https://learncodeweb.com/typescript/modules-in-typescript-explain-with-an-example/)

View File

@@ -1,12 +1,7 @@
# Extract
Extract constructs a type by extracting from Type all union members that are assignable to Union.
Extract allows you to create a new type by picking out specific types from a union based on a condition. Essentially, it filters a union type, keeping only those members that are assignable to a specified type. This is useful when you need to narrow down the possible types in a union to only those that meet a certain criteria.
```typescript
type T0 = Extract<'a' | 'b' | 'c', 'a' | 'f'>;
// ^ = type T0 = "a"
```
Visit the following resources to learn more:
Learn more from the following links:
- [@official@Extract<Type, Union>](https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union)
- [@official@Extract<Type, Union>](https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union)

View File

@@ -1,9 +1,9 @@
# Formatting
Prettier is an opinionated code formatter with support for JavaScript, HTML, CSS, YAML, Markdown, GraphQL Schemas. By far the biggest reason for adopting Prettier is to stop all the on-going debates over styles. Biome is a faster alternative to Prettier! (It also does linting!)
Formatting tools automatically adjust the way your code looks, making it consistent and easier to read. These tools can handle things like spacing, indentation, and line breaks. This makes your code cleaner and helps everyone on a team follow the same style. A popular tool for formatting code is Prettier. It supports TypeScript and can be configured to enforce a specific style guide.
Visit the following resources to learn more:
- [@article@Prettier Website](https://prettier.io)
- [@article@Why Prettier](https://prettier.io/docs/en/why-prettier.html)
- [@article@BiomeJS Website](https://biomejs.dev)
- [@article@BiomeJS Website](https://biomejs.dev)

View File

@@ -1,19 +1,7 @@
# Function Overloading
Function Overloading in TypeScript allows multiple functions with the same name but with different parameters to be defined. The correct function to call is determined based on the number, type, and order of the arguments passed to the function at runtime.
Function overloading allows you to define multiple function signatures with the same name but different parameter types or numbers of parameters. This lets you provide specific type information based on how the function is called, enhancing type safety and code clarity. When you call an overloaded function, TypeScript picks the most appropriate function signature based on the provided arguments.
```typescript
function add(a: number, b: number): number;
function add(a: string, b: string): string;
Visit the following resources to learn more:
function add(a: any, b: any): any {
return a + b;
}
console.log(add(1, 2)); // 3
console.log(add('Hello', ' World')); // "Hello World"
```
Learn more from the following links:
- [@official@Function Overloads](https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads)
- [@official@Function Overloads](https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads)

View File

@@ -1,27 +1,7 @@
# Generic Constraints
Generic constraints in TypeScript allow you to specify the requirements for the type parameters used in a generic type. These constraints ensure that the type parameter used in a generic type meets certain requirements.
Generic constraints in TypeScript allow you to limit the types that can be used as type arguments for a generic type or function. They ensure that the type argument satisfies a specific requirement, like having certain properties or methods. This provides more type safety and enables you to work with specific properties of the generic type, knowing they are guaranteed to exist.
Constraints are specified using the `extends` keyword, followed by the type that the type parameter must extend or implement.
Visit the following resources to learn more:
```typescript
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
// Now we know it has a .length property, so no more error
console.log(arg.length);
return arg;
}
loggingIdentity(3); // Error, number doesn't have a .length property
loggingIdentity({ length: 10, value: 3 }); // OK
```
In this example, the `Lengthwise` interface defines a `length` property. The `loggingIdentity` function uses a generic type parameter `T` that is constrained by the `Lengthwise` interface, meaning that the type parameter must extend or implement the `Lengthwise` interface. This constraint ensures that the length property is available on the argument passed to the `loggingIdentity` function.
Learn more from the following resources:
- [@official@Generic Constraints - TypeScript](https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints)
- [@official@Generic Constraints - TypeScript](https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints)

View File

@@ -1,36 +1,7 @@
# Generic Types
Generic types in TypeScript allow you to write objects, functions and classes that work with multiple data types, instead of being limited to a single data type. A generic type is defined using angle brackets `<T>` and can be used as a placeholder for a specific data type. The actual data type is specified when the function or class is used.
Generic types allow you to write code that can work with a variety of types without sacrificing type safety. Think of them as placeholders for types that you specify later when you use the code. To create a generic type, you use angle brackets `<>` to define type parameters. These parameters act as variables that represent the specific type you want to work with, allowing you to write reusable components that adapt to different data types.
For example, the following is a generic function that takes a single argument of any data type and returns the same data type:
Visit the following resources to learn more:
```typescript
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>('Hello'); // type of output will be 'string'
```
In this example, the `identity` function takes a single argument of any data type and returns the same data type. The actual data type is specified when the function is called by using `<string>` before the argument `Hello`.
Generics can also be used with classes, interfaces, and object types, allowing them to work with multiple data types as well.
For example:
```typescript
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
return x + y;
};
```
Learn more from the following resources:
- [@official@Hello World of Generics](https://www.typescriptlang.org/docs/handbook/2/generics.html#hello-world-of-generics)
- [@official@Hello World of Generics](https://www.typescriptlang.org/docs/handbook/2/generics.html#hello-world-of-generics)

View File

@@ -1,19 +1,7 @@
# Generics
Generics in TypeScript are a way to write code that can work with multiple data types, instead of being limited to a single data type. Generics allow you to write functions, classes, and interfaces that take one or more type parameters, which act as placeholders for the actual data types that will be used when the function, class, or interface is used.
Generics are a way to write code that can work with a variety of types without knowing those types ahead of time. They allow you to define type variables that can be used to represent the specific type that will be used when the code is actually executed. This makes your code more reusable and type-safe by preventing errors that could occur if you were to use `any` or other less specific types.
For example, the following is a generic function that takes a single argument of any data type and returns the same data type:
Visit the following resources to learn more:
```typescript
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>('Hello'); // type of output will be 'string'
```
In this example, the `identity` function takes a single argument of any data type and returns the same data type. The actual data type is specified when the function is called by using `<string>` before the argument `"Hello"`.
Learn more from the following resources:
- [@official@Hello World of Generics](https://www.typescriptlang.org/docs/handbook/2/generics.html#hello-world-of-generics)
- [@official@Hello World of Generics](https://www.typescriptlang.org/docs/handbook/2/generics.html#hello-world-of-generics)

View File

@@ -1,27 +1,7 @@
# Global Augmentation
In TypeScript, global augmentation is a way to add declarations to the global scope. This is useful when you want to add new functionality to existing libraries or to augment the built-in types in TypeScript.
Global augmentation in TypeScript lets you add or modify existing global types and interfaces. This is particularly useful when working with JavaScript libraries that don't have TypeScript definitions or when you want to extend existing TypeScript definitions to suit your specific project needs. It essentially allows you to declare properties or methods on globally available objects (like `window` or built-in JavaScript objects) from within your TypeScript code.
Here's an example of how you can use global augmentation in TypeScript:
Visit the following resources to learn more:
```typescript
// myModule.d.ts
declare namespace NodeJS {
interface Global {
myGlobalFunction(): void;
}
}
// main.ts
global.myGlobalFunction = function () {
console.log('I am a global function!');
};
myGlobalFunction(); // Output: "I am a global function!"
```
In this example, we declare a new namespace "NodeJS" and add an interface "Global" to it. Within the "Global" interface, we declare a new function "myGlobalFunction".
Learn more from the following links:
- [@official@Global augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation)
- [@official@Global augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation)

View File

@@ -1,26 +1,3 @@
# Hybrid Types
In TypeScript, a hybrid type is a type that combines multiple types into a single type. The resulting type is considered a union of those types. This allows you to specify that a value can have multiple types, rather than just one.
For example, you can create a hybrid type that can accept either a string or a number:
```typescript
type StringOrNumber = string | number;
```
You can also use hybrid types to create more complex types that can represent a combination of several different types of values. For example:
```typescript
type Education = {
degree: string;
school: string;
year: number;
};
type User = {
name: string;
age: number;
email: string;
education: Education;
};
```
Hybrid types describe objects that act as both an object and a function. In essence, they possess properties and methods like a regular object, but they can also be invoked or called directly like a function. This unusual structure is often used when a function needs to maintain state or have additional properties associated with it.

View File

@@ -1,40 +1,8 @@
# Inheritance vs Polymorphism
# Inheritance vs. Polymorphism
Inheritance and polymorphism are two fundamental concepts in object-oriented programming, and they are supported in TypeScript as well.
Inheritance is a mechanism where a class (the subclass or derived class) acquires the properties and methods of another class (the superclass or base class), establishing an "is-a" relationship. Polymorphism, meaning "many forms," allows objects of different classes to be treated as objects of a common type, enabling you to write code that can work with objects of multiple classes without knowing their specific types at compile time.
Inheritance refers to a mechanism where a subclass inherits properties and methods from its parent class. This allows a subclass to reuse the code and behavior of its parent class while also adding or modifying its own behavior. In TypeScript, inheritance is achieved using the extends keyword.
Polymorphism refers to the ability of an object to take on many forms. This allows objects of different classes to be treated as objects of a common class, as long as they share a common interface or inheritance hierarchy. In TypeScript, polymorphism is achieved through method overriding and method overloading.
```typescript
class Animal {
makeSound(): void {
console.log('Making animal sound');
}
}
class Dog extends Animal {
makeSound(): void {
console.log('Bark');
}
}
class Cat extends Animal {
makeSound(): void {
console.log('Meow');
}
}
let animal: Animal;
animal = new Dog();
animal.makeSound(); // Output: Bark
animal = new Cat();
animal.makeSound(); // Output: Meow
```
Learn more from the following resources:
Visit the following resources to learn more:
- [@article@Dev.to - Mastering OOP in TypeScript](https://dev.to/rajrathod/mastering-object-oriented-programming-with-typescript-encapsulation-abstraction-inheritance-and-polymorphism-explained-c6p)
- [@video@Inheritance and Polymorphism In TypeScript](https://www.youtube.com/watch?v=Sn6K57YSuwU)
- [@video@Inheritance and Polymorphism In TypeScript](https://www.youtube.com/watch?v=Sn6K57YSuwU)

View File

@@ -1,49 +1,8 @@
# Install and Configure
# Installation and Configuration
To install and configure TypeScript in your project, you need to perform the following steps:
The installation process of TypeScript generally includes installing the TypeScript compiler, which translates TypeScript code into JavaScript, and configuring your project with a `tsconfig.json` file to manage compiler options and project settings. This setup enables you to write, compile, and run TypeScript code effectively.
- Initialize npm in your project directory by running the following command:
```bash
npm init
```
- Install TypeScript as a project dependency by running the following command:
```bash
npm install --save-dev typescript
```
- Create a `tsconfig.json` file in your project directory to specify the compiler options for building your project. For example:
```json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src"
},
"exclude": ["node_modules"]
}
```
- Compile your TypeScript code using the following command:
```bash
npx tsc
```
Note: You can also compile individual TypeScript files by specifying the file path after the tsc command. For example:
```bash
npx tsc ./src/index.ts
```
And you're all set! You can now start writing TypeScript code in your project.
Learn more from the following links:
Visit the following resources to learn more:
- [@official@Install and Configure TypeScript](https://www.typescriptlang.org/download)
- [@article@TypeScript Getting Started](https://thenewstack.io/typescript-tutorial-a-guide-to-using-the-programming-language/)
- [@article@TypeScript Getting Started](https://thenewstack.io/typescript-tutorial-a-guide-to-using-the-programming-language/)

View File

@@ -1,27 +1,7 @@
# instanceof operator
# instanceof Operator
The `instanceof` operator is a way to narrow down the type of a variable. It is used to check if an object is an instance of a class.
The `instanceof` operator checks if an object is an instance of a specific class or constructor function. It determines if the prototype property of a constructor appears anywhere in the prototype chain of an object. The result of this check is a boolean value, indicating whether the object is considered an instance of the specified type.
```typescript
class Bird {
fly() {
console.log('flying...');
}
layEggs() {
console.log('laying eggs...');
}
}
Visit the following resources to learn more:
const pet = new Bird();
// instanceof
if (pet instanceof Bird) {
pet.fly();
} else {
console.log('pet is not a bird');
}
```
Learn more from the following links:
- [@official@instanceOf Operator](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#instanceof-narrowing)
- [@official@instanceOf Operator](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#instanceof-narrowing)

View File

@@ -1,29 +1,7 @@
# InstanceType
This type constructs a type consisting of the instance type of a constructor function in Type.
`InstanceType` is a conditional type in TypeScript that extracts the instance type of a constructor function type. In simpler terms, given a type that represents a class or a constructor function, `InstanceType` determines the type of the object that would be created when you use the `new` keyword with that constructor. This allows you to easily work with the specific type of instances generated by a class constructor within your type system.
```typescript
class C {
x = 0;
y = 0;
}
Visit the following resources to learn more:
type T0 = InstanceType<typeof C>;
// type T0 = C
type T1 = InstanceType<any>;
// type T1 = any
type T2 = InstanceType<never>;
// type T2 = never
type T3 = InstanceType<string>;
// ^ Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
type T4 = InstanceType<Function>;
// ^ Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.
```
Learn more from the following links:
- [@official@InstanceType`<Type>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#instancetypetype)
- [@official@InstanceType<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#instancetypetype)

View File

@@ -1,21 +1,7 @@
# Interface Declaration
An `interface` in TypeScript is a blueprint for creating objects with specific structure. An `interface` defines a set of properties, methods, and events that a class or object must implement. The interface is a contract between objects and classes and can be used to enforce a specific structure for objects in your code.
An interface declaration introduces a new named type into the TypeScript type system. It specifies a contract that an object (or other type) can adhere to, defining the names and types of properties and methods that implementing objects must possess. Interfaces do not produce JavaScript code; they exist purely for type-checking purposes, enabling stronger static typing and improved code maintainability.
Here is an example of an interface declaration in TypeScript:
Visit the following resources to learn more:
```typescript
interface Person {
firstName: string;
lastName: string;
age?: number;
getFullName(): string;
}
```
In this example, the Person interface defines four properties: `firstName`, `lastName`, `age`, and a method `getFullName()`. The age property is optional, indicated by the `?` symbol. Any class or object that implements the `Person` interface must have these properties and method.
Learn more from the following links:
- [@official@Extending Interfaces](https://www.typescriptlang.org/docs/handbook/2/objects.html)
- [@official@Extending Interfaces](https://www.typescriptlang.org/docs/handbook/2/objects.html)

View File

@@ -1,18 +1,7 @@
# Interface
TypeScript allows you to specifically type an object using an interface that can be reused by multiple objects.
An interface in TypeScript is a way to define a contract for the shape of an object. It names a set of properties and their types that an object must have. Think of it as a blueprint that specifies the properties (and optionally, methods) that an object should possess, allowing you to ensure that different parts of your code work together smoothly by enforcing a consistent structure.
```typescript
interface Person {
name: string;
age: number;
}
Visit the following resources to learn more:
function greet(person: Person) {
return 'Hello ' + person.name;
}
```
Learn more from the following links:
- [@official@Object Types - Interfaces](https://www.typescriptlang.org/docs/handbook/2/objects.html)
- [@official@Object Types - Interfaces](https://www.typescriptlang.org/docs/handbook/2/objects.html)

View File

@@ -1,17 +1,7 @@
# Intersection Types
An intersection type creates a new type by combining multiple existing types. The new type has all features of the existing types.
Intersection types in TypeScript allow you to combine multiple types into a single type. The resulting type has all the features (properties, methods, etc.) of all the constituent types. This is particularly useful when you want to create a type that represents an object that must satisfy multiple type constraints simultaneously.
To combine types, you use the `&` operator as follows:
Visit the following resources to learn more:
```typescript
type typeAB = typeA & typeB;
```
The `typeAB` will have all properties from both typeA and typeB.
Note that the union type uses the `|` operator that defines a variable which can hold `typeA` value, or `typeB` value, or both altogether.
Learn more from the following links:
- [@article@Intersection Types in TypeScript](https://www.typescripttutorial.net/typescript-tutorial/typescript-intersection-types/)
- [@article@Intersection Types in TypeScript](https://www.typescripttutorial.net/typescript-tutorial/typescript-intersection-types/)

View File

@@ -1,18 +1,10 @@
# TypeScript
# Introduction to TypeScript
TypeScript is a statically-typed programming language that is a superset of JavaScript. It was developed and is maintained by Microsoft. TypeScript was created to address the challenges of building large-scale JavaScript applications and adds optional type annotations, classes, interfaces, and other features to the language.
TypeScript is a programming language that builds on JavaScript by adding static types. It essentially acts as a superset of JavaScript, meaning that all valid JavaScript code is also valid TypeScript code. The key addition of static typing allows developers to define the expected data types of variables, function parameters, and return values, which helps catch errors during development and improves code maintainability.
The main benefits of using TypeScript include:
- Type Safety
- Improved Tooling
- Improved Maintainability
- Backwards Compatibility
Learn more from the following links:
Visit the following resources to learn more:
- [@official@Overview of TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html)
- [@official@TypeScript Official Handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
- [@article@What Is TypeScript?](https://thenewstack.io/what-is-typescript/)
- [@video@Video: Where TypeScript Excels](https://youtu.be/BUo7B6UuoJ4)
- [@feed@Explore top posts about TypeScript](https://app.daily.dev/tags/typescript?ref=roadmapsh)
- [@video@Video: Where TypeScript Excels](https://youtu.be/BUo7B6UuoJ4)

View File

@@ -1,20 +1,7 @@
# keyof Operator
The `keyof` operator in TypeScript is used to get the union of keys from an object type. Here's an example of how it can be used:
The `keyof` operator in TypeScript creates a union of all the keys (property names) of a given object type. It essentially extracts the names of the properties as string literal types. This allows you to work with the properties of an object type in a type-safe way, especially when dealing with generic functions or situations where you need to ensure that you're only accessing valid properties.
```typescript
interface User {
name: string;
age: number;
location: string;
}
Visit the following resources to learn more:
type UserKeys = keyof User; // "name" | "age" | "location"
const key: UserKeys = 'name';
```
In this example, `UserKeys` is a type that represents the union of keys from the `User` interface, which is `"name"` | `"age"` | `"location"`. And a constant named `key` with the type `UserKeys` is declared with the value `"name"`.
Learn more from the following links:
- [@official@keyof Type Operator](https://www.typescriptlang.org/docs/handbook/2/keyof-types.html#handbook-content)
- [@official@keyof Type Operator](https://www.typescriptlang.org/docs/handbook/2/keyof-types.html#handbook-content)

View File

@@ -1,9 +1,9 @@
# Linting
With ESLint you can impose the coding standard using a certain set of standalone rules.
Linting is the process of running a program that analyzes code for potential errors, stylistic issues, and code quality problems. It helps developers identify and fix issues early in the development cycle, leading to more maintainable and consistent codebases. ESLint is a popular linting tool for JavaScript and TypeScript that can be configured with rules to enforce specific coding standards and best practices.
Visit the following resources to learn more:
- [@article@ESLint Official Website](https://eslint.org/)
- [@article@Introduction to ESLint](https://dev.to/shivambmgupta/eslint-what-why-when-how-5f1d)
- [@video@ESLint Quickstart - find errors automatically](https://www.youtube.com/watch?v=qhuFviJn-es)
- [@video@ESLint Quickstart - find errors automatically](https://www.youtube.com/watch?v=qhuFviJn-es)

View File

@@ -1,18 +1,7 @@
# Literal Types
Literal types in TypeScript are a way to specify a value exactly, rather than just a type. Literal types can be used to enforce that a value must be of a specific type and a specific value. Literal types are created by using a literal value, such as a string, number, or boolean, as a type.
Literal types are a feature that allows you to specify the exact value a variable can hold. Instead of just saying a variable is a `string` or a `number`, you can specify that it can only be a particular string like `"hello"` or a particular number like `42`. This enables more precise type checking and helps catch errors at compile time by ensuring that variables only hold the intended values.
For example, the following is a literal type that represents a value of 42:
Visit the following resources to learn more:
```typescript
type Age = 42;
let age: Age = 42; // ok
let age: Age = 43; // error
```
In this example, the `Age` literal type is created by using the number `42` as a type. This type can then be used to enforce that a value must be of type `number` and have the value `42`.
Learn more from the following links:
- [@official@Literal Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types)
- [@official@Literal Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types)

View File

@@ -1,20 +1,7 @@
# Mapped Types
Mapped types in TypeScript are a way to create a new type based on an existing type, where each property of the existing type is transformed in some way. Mapped types are declared using a combination of the `keyof` operator and a type that maps each property of the existing type to a new property type.
Mapped types in TypeScript allow you to create new types based on existing ones by transforming each property. They iterate over the keys of an existing type and apply a transformation to each key and/or value, effectively mapping the original type to a new type structure. This provides a concise and powerful way to generate types that are variations of other types, promoting code reuse and reducing redundancy.
For example, the following is a mapped type that takes an object type and creates a new type with all properties of the original type but with their type changed to `readonly`:
Visit the following resources to learn more:
```typescript
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
let obj = { x: 10, y: 20 };
let readonlyObj: Readonly<typeof obj> = obj;
```
In this example, the `Readonly` mapped type takes an object type `T` and creates a new type with all properties of `T` but with their type changed to `readonly`. The keyof `T` operator is used to extract the names of the properties of `T`, and the `T[P]` syntax is used to access the type of each property of `T`. The `readonly` keyword is used to make the properties of the new type `readonly`.
Learn more from the following links:
- [@official@Mapped Types](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#handbook-content)
- [@official@Mapped Types](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#handbook-content)

View File

@@ -1,30 +1,7 @@
# Method Overriding
In TypeScript, method overriding is a mechanism where a subclass provides a new implementation for a method that is already defined in its parent class. This allows the subclass to inherit the behavior of the parent class, but change its behavior to fit its own needs.
Method overriding allows a subclass to provide a specific implementation for a method that is already defined in its superclass. When a method in a subclass has the same name, same parameters, and same return type (or a more specific return type, known as covariant return type) as a method in its superclass, the subclass's method overrides the superclass's method. This means that when the method is called on an object of the subclass, the subclass's version of the method will be executed instead of the superclass's version.
To override a method in TypeScript the signature of the method in the subclass must match exactly with the signature of the method in the parent class.
Visit the following resources to learn more:
```typescript
class Animal {
makeSound(): void {
console.log('Making animal sound');
}
}
class Dog extends Animal {
makeSound(): void {
console.log('Bark');
}
}
let animal: Animal;
animal = new Dog();
animal.makeSound(); // Output: Bark
```
In this example, the `Dog` class overrides the makeSound method defined in the Animal class and provides its own implementation. When the `makeSound` method is called on an instance of the `Dog` class, it will use the implementation in the `Dog` class rather than the implementation in the `Animal` class.
Learn more from the following resources:
- [@official@TypeScript - Overriding Methods](https://www.typescriptlang.org/docs/handbook/2/classes.html#overriding-methods)
- [@official@TypeScript - Overriding Methods](https://www.typescriptlang.org/docs/handbook/2/classes.html#overriding-methods)

View File

@@ -1,33 +1,7 @@
# Namespace Augmentation
In TypeScript, namespace augmentation is a way to extend or modify existing namespaces. This is useful when you want to add new functionality to existing namespaces or to fix missing or incorrect declarations in third-party libraries.
Namespace augmentation in TypeScript allows you to add new properties or methods to an existing namespace, even if that namespace is defined in a separate file or module. This feature is particularly useful for extending namespaces declared in external libraries or modules without directly modifying the original source code. It provides a way to customize or add functionality to existing namespaces in a modular and organized manner.
Here's an example of how you can use namespace augmentation in TypeScript:
Visit the following resources to learn more:
```typescript
// myModule.d.ts
declare namespace MyModule {
export interface MyModule {
newFunction(): void;
}
}
// main.ts
/// <reference path="myModule.d.ts" />
namespace MyModule {
export class MyModule {
public newFunction() {
console.log('I am a new function in MyModule!');
}
}
}
const obj = new MyModule.MyModule();
obj.newFunction(); // Output: "I am a new function in MyModule!"
```
In this example, we use namespace augmentation to add a new function "newFunction" to the "MyModule" namespace. This is done in the declaration file `myModule.d.ts` by declaring a new interface "MyModule" within the "MyModule" namespace and adding the "newFunction" function to it.
Learn more from the following links:
- [@official@Module Augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)
- [@official@Module Augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)

View File

@@ -1,26 +1,9 @@
# Namespaces
In TypeScript, namespaces are used to organize and share code across multiple files. Namespaces allow you to group related functionality into a single unit and prevent naming conflicts.
Namespaces in TypeScript are a way to organize code into logical groups, preventing naming collisions and improving code maintainability. They create a named container where you can define variables, functions, classes, and interfaces. By using namespaces, you can encapsulate related functionality under a specific name, making your code more structured and easier to understand.
Here's an example of how you can use namespaces in TypeScript:
```typescript
// myNamespace.ts
namespace MyNamespace {
export function doSomething() {
console.log('Doing something...');
}
}
// main.ts
/// <reference path="myNamespace.ts" />
MyNamespace.doSomething(); // Output: "Doing something..."
```
In this example, we use the `namespace` keyword in the "myNamespace.ts" file to define a namespace "MyNamespace". Within the namespace, we export a function "doSomething".
Learn more from the following resources:
Visit the following resources to learn more:
- [@official@Overview of Namespaces](https://www.typescriptlang.org/docs/handbook/namespaces.html)
- [@official@Namespaces and Modules](https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html)
- [@official@TypeScript - Using Namespaces](https://typescriptlang.org/docs/handbook/namespaces-and-modules.html#using-namespaces)
- [@official@TypeScript - Using Namespaces](https://typescriptlang.org/docs/handbook/namespaces-and-modules.html#using-namespaces)

View File

@@ -1,28 +1,7 @@
# Never
# Never Type
The `never` type represents the type of values that never occur. For instance, `never` is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns. Variables also acquire the type never when narrowed by any type guards that can never be `true`.
The `never` type in TypeScript represents the type of values that will never occur. This means a function that always throws an error or runs forever (infinite loop) implicitly returns `never`. It is also useful for exhaustive checking in discriminated unions, ensuring that all possible cases are handled. Essentially, you cannot assign any type to a variable of type `never` (except `never` itself), making it the bottom type in TypeScript's type system.
The never type is a subtype of, and assignable to, every type; however, no type is a subtype of, or assignable to, `never` (except `never` itself). Even any isnt assignable to `never`.
Visit the following resources to learn more:
Examples of functions returning never:
```typescript
// Function returning never must not have a reachable end point
function error(message: string): never {
throw new Error(message);
}
// Inferred return type is never
function fail() {
return error('Something failed');
}
// Function returning never must not have a reachable end point
function infiniteLoop(): never {
while (true) {}
}
```
Learn more from the following links:
- [@official@Never Type](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-never-type)
- [@official@Never Type](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-never-type)

View File

@@ -1,16 +1,7 @@
# Non Null Assertion
# Non-null Assertion
The non-null assertion operator (!) is a type assertion in TypeScript that allows you to tell the compiler that a value will never be null or undefined.
The non-null assertion operator in TypeScript is a way to tell the compiler that you are certain a value is not null or undefined, even if the TypeScript's type checker thinks it could be. It is denoted by an exclamation mark (`!`) placed after a variable or expression. Using this operator effectively tells the compiler to suppress strict null checks for that particular expression, trusting that you, the developer, have enough context to know the value will be present at runtime.
```typescript
let name: string | null = null;
Visit the following resources to learn more:
// we use the non-null assertion operator to tell the compiler that name will never be null
let nameLength = name!.length;
```
The non-null assertion operator is used to assert that a value is not null or undefined, and to tell the compiler to treat the value as non-nullable. However, it's important to be careful when using the non-null assertion operator, as it can lead to runtime errors if the value is actually `null` or `undefined`.
Learn more from the following links:
- [@official@Non-null assertion operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator)
- [@official@Non-null assertion operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator)

View File

@@ -1,15 +1,3 @@
# Non Nullable
# NonNullable Utility Type
Non-Nullable constructs a type by excluding `null` and `undefined` from Type.
```typescript
type T0 = NonNullable<string | number | undefined>;
// type T0 = string | number
type T1 = NonNullable<string[] | null | undefined>;
// type T1 = string[]
```
Learn more from the following links:
- [@official@NonNullable<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype)
`NonNullable` is a utility type that removes `null` and `undefined` from a type. If you have a type that could potentially be `null` or `undefined`, applying `NonNullable` ensures that the resulting type will only consist of the original type's other possible values, effectively guaranteeing that `null` and `undefined` are excluded.

View File

@@ -1,23 +1,7 @@
# null
# Null Type in TypeScript
JavaScript has two primitive values used to signal absent or uninitialized value: `null` (absent) and `undefined` (unintialized).
The `null` type represents the intentional absence of a value. It's a primitive data type that has only one possible value: `null`. It signifies that a variable or property has no value assigned to it, or that a value has been explicitly removed.
TypeScript has two corresponding _types_ by the same names. How these types behave depends on whether you have the `strictNullChecks` option on.
Visit the following resources to learn more:
With `strictNullChecks` off, values that might be `null` or `undefined` can still be accessed normally, and the values `null` and `undefined` can be assigned to a property of any type. This is similar to how languages without `null` checks (e.g. C#, Java) behave. The lack of checking for these values tends to be a major source of bugs; TypeScript always recommend people turn `strictNullChecks` on if its practical to do so in the codebase.
With `strictNullChecks` on, when a value is `null` or `undefined`, you will need to test for those values before using methods or properties on that value. Just like checking for `undefined` before using an optional property, we can use narrowing to check for values that might be `null`:
```typescript
function doSomething(x: string | null) {
if (x === null) {
// do nothing
} else {
console.log('Hello, ' + x.toUpperCase());
}
}
```
Learn more from the following links:
- [@official@null and undefined](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined)
- [@official@null and undefined](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined)

View File

@@ -1,12 +1,7 @@
# number
# Number Type in TypeScript
It is a primitive data type in TypeScript that represents numeric values. It includes both integer and floating-point values.
The `number` type in TypeScript represents numeric values. This includes integers (whole numbers like 1, 42, -10) and floating-point numbers (numbers with decimal points like 3.14, -0.5). TypeScript uses double-precision 64-bit floating point format (IEEE 754) to represent all numbers.
```typescript
let intValue: number = 42;
let floatValue: number = 3.14;
```
Visit the following resources to learn more:
Learn more from the following links:
- [@official@Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean)
- [@official@Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean)

View File

@@ -1,19 +1,7 @@
# Object
# Object Types in TypeScript
To define an `object` type, we simply list its properties and their types.
In TypeScript, an object type defines the structure of a JavaScript object. It specifies the names, types, and optionality of the properties an object should have. You can define object types using curly braces `{}` and listing the properties with their corresponding types, separated by semicolons or commas. This allows TypeScript to enforce that objects conform to a specific shape, enhancing code safety and providing better autocompletion during development.
For example, heres a function that takes a point-like object:
Visit the following resources to learn more:
```typescript
// The parameter's type annotation is an object type
function printCoord(pt: { x: number; y: number }) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3, y: 7 });
```
Learn more from the following links:
- [@official@Object Types in TypeScript](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#object-types)
- [@official@Object Types in TypeScript](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#object-types)

View File

@@ -1,31 +1,7 @@
# Omit
Omit constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals).
`Omit` is a utility type in TypeScript that constructs a new type by picking all properties from an existing type and then removing the specified properties (keys). Essentially, it creates a subset of the original type by excluding certain keys you define. The resulting type will only contain the properties that were not omitted.
```typescript
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
Visit the following resources to learn more:
type TodoPreview = Omit<Todo, 'description'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
createdAt: 1615544252770,
};
type TodoInfo = Omit<Todo, 'completed' | 'createdAt'>;
const todoInfo: TodoInfo = {
title: 'Pick up kids',
description: 'Kindergarten closes at 5pm',
};
```
Learn more from the following links:
- [@official@Omit<Type, Keys>](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)
- [@official@Omit<Type, Keys>](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)

View File

@@ -1,37 +1,3 @@
# Parameters
# Parameters Utility Type
Parameters constructs a tuple type from the types used in the parameters of a function type Type.
```typescript
type T0 = Parameters<() => string>;
// type T0 = []
type T1 = Parameters<(s: string) => void>;
// type T1 = [s: string]
type T2 = Parameters<<T>(arg: T) => T>;
// type T2 = [arg: unknown]
declare function f1(arg: { a: number; b: string }): void;
type T3 = Parameters<typeof f1>;
// type T3 = [arg: {
// a: number;
// b: string;
// }]
type T4 = Parameters<any>;
// type T4 = unknown[]
type T5 = Parameters<never>;
// type T5 = never
type T6 = Parameters<string>;
// ^ Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T7 = Parameters<Function>;
// ^ Type 'Function' does not satisfy the constraint '(...args: any) => any'.
```
Learn more from the following links:
- [@official@Parameters<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype)
The `Parameters` utility type in TypeScript extracts the parameter types of a function type into a tuple. This allows you to programmatically determine the expected arguments of a function and use them in other type definitions, providing type safety and flexibility when working with function signatures. The result is a tuple type where each element represents the type of a parameter in the function.

View File

@@ -1,31 +1,3 @@
# Partial
# Partial Type
The Partial type in TypeScript allows you to make all properties of a type optional. This is useful when you need to create an object with only a subset of the properties of an existing type.
Here's an example of using the Partial type in TypeScript:
```typescript
interface User {
name: string;
age: number;
email: string;
}
function createUser(user: Partial<User>): User {
return {
name: 'John Doe',
age: 30,
email: 'john.doe@example.com',
...user,
};
}
const newUser = createUser({ name: 'Jane Doe' });
console.log(newUser);
// Output: { name: 'Jane Doe', age: 30, email: 'john.doe@example.com' }
```
Learn more from the following links:
- [@official@Partial<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)
The `Partial<Type>` utility type in TypeScript constructs a type where all properties of the original `Type` are set to optional. This means that when you use `Partial<Type>`, you can create objects that only include a subset of the properties defined in the original `Type`, or even have no properties at all. Essentially, it makes all properties of a type nullable.

View File

@@ -1,22 +1,7 @@
# Pick
Pick constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type.
`Pick` is a utility type that constructs a new type by selecting a set of properties from an existing type. You specify which properties you want to include in the new type using their keys. This is useful when you need a subset of properties from a larger type definition.
```typescript
interface Todo {
title: string;
description: string;
completed: boolean;
}
Visit the following resources to learn more:
type TodoPreview = Pick<Todo, 'title' | 'completed'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
};
```
Learn more from the following links:
- [@official@Pick<Type, Keys>](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys)
- [@official@Pick<Type, Keys>](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys)

View File

@@ -1,20 +1,3 @@
# Readonly
Readonly constructs a type with all properties of Type set to readonly, meaning the properties of the constructed type cannot be reassigned.
```typescript
interface Todo {
title: string;
}
const todo: Readonly<Todo> = {
title: 'Delete inactive users',
};
// Cannot assign to 'title' because it is a read-only property.
todo.title = 'Hello';
```
Learn more from the following links:
- [@official@Readonly<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)
The `Readonly` utility type in TypeScript constructs a new type where all properties of the original type are set as read-only. This means that once a property is initialized, its value cannot be changed later. This is useful for creating immutable objects and ensuring that data is not accidentally modified.

View File

@@ -1,22 +1,7 @@
# Record
# Record Utility Type
Record constructs an object type whose property keys are Keys and whose property values are Type. This utility can be used to map the properties of a type to another type.
The `Record` utility type in TypeScript is used to construct a new type where the keys are of a specific type (typically a string, number, or symbol) and the values are of another specified type. This is useful when you want to define an object structure with a predefined set of keys and a consistent type for the values associated with those keys. Essentially, it's a shorthand for defining object types with specific key-value pairings.
```typescript
interface CatInfo {
age: number;
breed: string;
}
Visit the following resources to learn more:
type CatName = 'miffy' | 'boris' | 'mordred';
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: 'Persian' },
boris: { age: 5, breed: 'Maine Coon' },
mordred: { age: 16, breed: 'British Shorthair' },
};
```
Learn more from the following links:
- [@official@Record<Keys, Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)
- [@official@Record<Keys, Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)

View File

@@ -1,23 +1,7 @@
# Recursive Types
Recursive types in TypeScript are a way to define a type that references itself. Recursive types are used to define complex data structures, such as trees or linked lists, where a value can contain one or more values of the same type.
Recursive types in TypeScript allow you to define types that refer to themselves. This is especially useful for representing data structures that have a nested or hierarchical structure, like trees or linked lists. By using recursion in type definitions, you can ensure that the type system accurately reflects the self-referential nature of these data structures, enabling strong type checking throughout your code.
For example, the following is a recursive type that represents a linked list:
Visit the following resources to learn more:
```typescript
type LinkedList<T> = {
value: T;
next: LinkedList<T> | null;
};
let list: LinkedList<number> = {
value: 1,
next: { value: 2, next: { value: 3, next: null } },
};
```
In this example, the `LinkedList` type is defined as a type that extends `T` and contains a property `next` of the same type `LinkedList<T>`. This allows us to create a linked list where each node contains a value of type `T` and a reference to the next node in the list.
Learn more from the following links:
- [@official@Recursive Types in TypeScript](https://www.typescriptlang.org/play/3-7/types-and-code-flow/recursive-type-references.ts.html)
- [@official@Recursive Types in TypeScript](https://www.typescriptlang.org/play/3-7/types-and-code-flow/recursive-type-references.ts.html)

View File

@@ -1,40 +1,3 @@
# ReturnType
Return type constructs a type consisting of the return type of function Type.
```typescript
type T0 = ReturnType<() => string>;
// type T0 = string
type T1 = ReturnType<(s: string) => void>;
// type T1 = void
type T2 = ReturnType<<T>() => T>;
// type T2 = unknown
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
// type T3 = number[]
declare function f1(): { a: number; b: string };
type T4 = ReturnType<typeof f1>;
// type T4 = {
// a: number;
// b: string;
// }
type T5 = ReturnType<any>;
// type T5 = any
type T6 = ReturnType<never>;
// type T6 = never
type T7 = ReturnType<string>;
// ^ Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T8 = ReturnType<Function>;
// ^ Type 'Function' does not satisfy the constraint '(...args: any) => any'.
```
Learn more from the following links:
- [@official@ReturnType<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype)
`ReturnType` is a utility type that extracts the return type of a function. Given a function type, `ReturnType<Type>` produces a new type that represents the type of value that the function returns. This is useful when you need to work with the output of a function without knowing its exact return type beforehand.

View File

@@ -1,21 +1,7 @@
# Running TypeScript
To run TypeScript code, you'll need to have a TypeScript compiler installed. Here's a general process to run TypeScript code:
Running TypeScript involves converting your `.ts` files into JavaScript files that can be executed by a JavaScript runtime environment, such as a web browser or Node.js. This conversion, known as compilation or transpilation, is performed by the TypeScript compiler (`tsc`). After compilation, the resulting JavaScript files can then be run in the appropriate environment, allowing you to leverage the benefits of TypeScript during development while maintaining compatibility with standard JavaScript execution environments.
- Write TypeScript code in a `.ts` file (e.g. `app.ts`)
- Compile the TypeScript code into JavaScript using the TypeScript compiler:
Visit the following resources to learn more:
```bash
tsc app.ts
```
- Run the generated JavaScript code using a JavaScript runtime environment such as Node.js:
```bash
node app.js
```
Learn more from the following link:
- [@official@Running your TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-tooling-in-5-minutes.html)
- [@feed@Explore top posts about TypeScript](https://app.daily.dev/tags/typescript?ref=roadmapsh)
- [@official@Running your TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-tooling-in-5-minutes.html)

View File

@@ -1,7 +1,7 @@
# satisfies Keyword
# Satisfies Keyword
The `satisfies` operator lets us validate that the type of an expression matches some type, without changing the resulting type of that expression.
The `satisfies` keyword in TypeScript is used to ensure that a value conforms to a specific type without explicitly declaring that type. This is particularly useful when you want to check that an object's structure matches a type definition but still allow TypeScript to infer a more specific type for the object's properties. It validates the shape of the value against the specified type, and if valid it retains the initial type information.
Learn more from the following resources:
Visit the following resources to learn more:
- [@official@satisfies Keyword](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator)
- [@official@satisfies Keyword](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator)

View File

@@ -1,11 +1,7 @@
# string
# String
It is a primitive data type in TypeScript that represents textual data. It is a set of elements of the 16-bit Unicode character set.
A string represents a sequence of characters. It's used to store and manipulate textual data, like words, sentences, or any sequence of symbols. Strings are typically enclosed in single quotes (`'...'`), double quotes (`"..."`), or backticks (`` `...` ``).
```typescript
let name: string = 'John Doe';
```
Visit the following resources to learn more:
Learn more from the following link
- [@official@Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean)
- [@official@Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean)

View File

@@ -1,18 +1,7 @@
# Template Literal Types
Template literal types in TypeScript are a way to manipulate string values as types. They allow you to create a type based on the result of string manipulation or concatenation. Template literal types are created using the backtick (``) character and string manipulation expressions within the type.
Template literal types in TypeScript are a way to create new string literal types by combining existing string literal types, much like template literals in JavaScript. They allow you to define string types that are composed of other string types with specific patterns or structures. This is done by embedding other types within a string literal definition, enabling you to enforce stricter type safety and create more descriptive types based on string manipulation.
For example, the following is a template literal type that concatenates two strings:
Visit the following resources to learn more:
```typescript
type Name = `Mr. ${string}`;
let name: Name = `Mr. Smith`; // ok
let name: Name = `Mrs. Smith`; // error
```
In this example, the `Name` template literal type is created by concatenating the string `"Mr. "` with the type `string`. This type can then be used to enforce that a value must be a string that starts with `"Mr. "`.
Learn more from the following links:
- [@official@Template Literal Types](https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html#handbook-content)
- [@official@Template Literal Types](https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html#handbook-content)

View File

@@ -1,19 +1,7 @@
# Truthiness
Truthiness might not be a word youll find in the dictionary, but its very much something youll hear about in JavaScript.
Truthiness in TypeScript, as in JavaScript, refers to the concept of a value evaluating to `true` when encountered in a Boolean context. Certain values are inherently "truthy" while others are "falsy." TypeScript uses this understanding to refine the type of a variable based on the outcome of a truthiness check, effectively narrowing its potential types to those that are compatible with a `true` outcome. This allows for more precise type checking within conditional blocks.
In JavaScript, we can use any expression in conditionals, `&&`s, `||`s, `if` statements, Boolean negations (`!`), and more. As an example, if statements dont expect their condition to always have the type boolean.
Visit the following resources to learn more:
```typescript
function getUsersOnlineMessage(numUsersOnline: number) {
if (numUsersOnline) {
return `There are ${numUsersOnline} online now!`;
}
return "Nobody's here. :(";
}
```
Learn more from the following links:
- [@official@Truthiness Narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#truthiness-narrowing)
- [@official@Truthiness Narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#truthiness-narrowing)

View File

@@ -1,28 +1,8 @@
# TS/JS Interoperability
# TS and JS Interoperability
TypeScript and JavaScript have full interoperability, meaning you can use TypeScript code in JavaScript projects and vice versa. TypeScript is a superset of JavaScript, which means that any valid JavaScript code is also valid TypeScript code.
TypeScript and JavaScript interoperability refers to the ability of TypeScript code to work seamlessly with existing JavaScript code and vice versa. This means you can use JavaScript libraries in your TypeScript projects and gradually migrate JavaScript code to TypeScript without rewriting everything at once. It allows for a smooth transition by leveraging existing codebases and libraries while adopting the benefits of TypeScript.
You can use JavaScript libraries in TypeScript projects by either including the JavaScript files directly or using type definitions for the library. Type definitions provide type information for JavaScript libraries, making it easier to use them in TypeScript.
On the other hand, you can use TypeScript code in JavaScript projects by simply compiling the TypeScript code into JavaScript. The generated JavaScript code can be used in any JavaScript environment, and it will work the same way as regular JavaScript code.
TypeScript's compiler also supports type checking for plain JavaScript code by adding the `// @ts-check` comment at the top of a file. This allows the compiler to validate types by inspecting the JSDoc comments:
```typescript
// @ts-check
/**
* Adds two numbers together.
* @param {number} a - The first number.
* @param {number} b - The second number.
* @returns {number} The sum of the two numbers.
*/
function add(a, b) {
return a + b;
}
```
Learn more from the following links:
Visit the following resources to learn more:
- [@official@Type Checking JavaScript Files](https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html)
- [@video@Using JavaScript in TypeScript](https://youtu.be/AZhZlEbBaB4)
- [@video@Using JavaScript in TypeScript](https://youtu.be/AZhZlEbBaB4)

View File

@@ -1,7 +1,9 @@
# ts-node
ts-node is a TypeScript execution and REPL for node.js, with source map and native ESM support. Learn more from the following links:
ts-node is a package that lets you directly run TypeScript code without needing to pre-compile it into JavaScript. It does this by providing a TypeScript execution environment for Node.js, allowing you to execute `.ts` files directly from the command line or by using it as a Node.js module. Essentially, it combines the TypeScript compiler (`tsc`) and Node.js into a single, streamlined process.
Visit the following resources to learn more:
- [@opensource@ts-node - GitHub Project](https://github.com/TypeStrong/ts-node)
- [@article@How To Run TypeScript Scripts with ts-node](https://www.digitalocean.com/community/tutorials/typescript-running-typescript-ts-node)
- [@feed@Explore top posts about TypeScript](https://app.daily.dev/tags/typescript?ref=roadmapsh)
- [@feed@Explore top posts about TypeScript](https://app.daily.dev/tags/typescript?ref=roadmapsh)

View File

@@ -1,8 +1,8 @@
# TS Playground
The TypeScript Playground is a great tool to learn TypeScript. It allows you to write TypeScript code and see the JavaScript output. It also allows you to share your code with others.
The TS Playground is an online, interactive environment that allows you to write, compile, and share TypeScript code directly in your web browser. It provides immediate feedback on your code, showing compilation errors and the resulting JavaScript output in real-time. This makes it a convenient tool for experimenting with TypeScript features, prototyping small projects, and quickly testing code snippets without needing a local development environment.
Learn more from the following links:
Visit the following resources to learn more:
- [@official@TypeScript Official - Playground](https://www.typescriptlang.org/play)
- [@feed@Explore top posts about TypeScript](https://app.daily.dev/tags/typescript?ref=roadmapsh)
- [@feed@Explore top posts about TypeScript](https://app.daily.dev/tags/typescript?ref=roadmapsh)

View File

@@ -1,24 +1,7 @@
# tsc
`tsc` is the command line tool for the TypeScript compiler. It compiles TypeScript code into JavaScript code, making it compatible with the browser or any JavaScript runtime environment.
`tsc` is the command-line compiler for TypeScript. It takes TypeScript code as input and transforms it into JavaScript code that can be executed by browsers or other JavaScript runtimes like Node.js. You use `tsc` to check for type errors, enforce coding standards, and ultimately prepare your TypeScript code for deployment.
You can use the `tsc` command to compile your TypeScript code by running the following command in your terminal or command prompt:
Visit the following resources to learn more:
```bash
tsc
```
This command will compile all TypeScript files in your project that are specified in your `tsconfig.json` file. If you want to compile a specific TypeScript file, you can specify the file name after the `tsc` command, like this:
```bash
tsc index.ts
```
The `tsc` command has several options and flags that you can use to customize the compilation process. For example, you can use the `--target` option to specify the version of JavaScript to compile to, or the `--outDir` option to specify the output directory for the compiled JavaScript files.
You can run `tsc --help` to see a list of all the available options and flags.
Learn more from the following links:
- [@official@tsc CLI Options](https://www.typescriptlang.org/docs/handbook/compiler-options.html#using-the-cli)
- [@feed@Explore top posts about TypeScript](https://app.daily.dev/tags/typescript?ref=roadmapsh)
- [@official@tsc CLI Options](https://www.typescriptlang.org/docs/handbook/compiler-options.html#using-the-cli)

View File

@@ -1,31 +1,7 @@
# tsconfig.json
tsconfig.json is a configuration file in TypeScript that specifies the compiler options for building your project. It helps the TypeScript compiler understand the structure of your project and how it should be compiled to JavaScript. Some common options include:
`tsconfig.json` is a configuration file that specifies how the TypeScript compiler should transpile your TypeScript code into JavaScript. It controls various compilation options such as target ECMAScript version, module system, and source maps. This file lives at the root of a TypeScript project and allows you to define the project's compilation settings in a declarative and reproducible manner.
- `target`: the version of JavaScript to compile to.
- `module`: the module system to use.
- `strict`: enables/disables strict type checking.
- `outDir`: the directory to output the compiled JavaScript files.
- `rootDir`: the root directory of the TypeScript files.
- `include`: an array of file/directory patterns to include in the compilation.
- `exclude`: an array of file/directory patterns to exclude from the compilation.
Visit the following resources to learn more:
Given below is the sample `tsconfig.json` file:
```json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src",
},
"exclude": ["node_modules"],
"include": ["src"]
}
```
Learn more from the following links:
- [@official@What is a tsconfig.json](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#handbook-content)
- [@official@What is a tsconfig.json](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#handbook-content)

View File

@@ -1,19 +1,7 @@
# Tuple
A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions.
A tuple is a typed array with a pre-defined length and types for each index. Each position in the tuple can have its own specific type, allowing you to create arrays with a known structure where the type of element is known at each index. Tuples ensure that the number of elements matches the defined length and that each element is of the expected type.
```typescript
type StringNumberPair = [string, number];
Visit the following resources to learn more:
const pair: StringNumberPair = ['hello', 42];
const first = pair[0];
const second = pair[1];
// Error: Index out of bounds
const third = pair[2];
```
Learn more from the following links:
- [@official@Tuple Types](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types)
- [@official@Tuple Types](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types)

View File

@@ -1,19 +1,7 @@
# Type Aliases
A Type Alias in TypeScript allows you to create a new name for a type.
Type aliases in TypeScript create a new name for an existing type. This new name can then be used anywhere you would normally use the original type. They don't create a new type; instead, they offer a more readable and convenient way to refer to potentially complex or frequently used types, such as unions, intersections, or tuple types.
Here's an example:
Visit the following resources to learn more:
```typescript
type Name = string;
type Age = number;
type User = { name: Name; age: Age };
const user: User = { name: 'John', age: 30 };
```
In the example above, `Name` and `Age` are type aliases for `string` and `number` respectively. And `User` is a type alias for an object with properties `name` of type `Name` and `age` of type `Age`.
Learn more from the following links:
- [@official@Type Aliases](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases)
- [@official@Type Aliases](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases)

View File

@@ -4,20 +4,19 @@ TypeScript uses structural typing to determine type compatibility. This means th
Here's an example of type compatibility in TypeScript:
```typescript
interface Point {
x: number;
y: number;
}
let p1: Point = { x: 10, y: 20 };
let p2: { x: number; y: number } = p1;
console.log(p2.x); // Output: 10
```
interface Point {
x: number;
y: number;
}
let p1: Point = { x: 10, y: 20 };
let p2: { x: number; y: number } = p1;
console.log(p2.x); // Output: 10
In this example, `p1` has the type `Point`, while `p2` has the type `{ x: number; y: number }`. Despite the fact that the two types have different names, they are considered compatible because they have the same structure. This means that you can assign a value of type `Point` to a variable of type `{ x: number; y: number }`, as we do with `p1` and `p2` in this example.
Learn more from the following links:
Visit the following resources to learn more:
- [@official@Type Compatibility](https://www.typescriptlang.org/docs/handbook/type-compatibility.html)
- [@official@Type Compatibility](https://www.typescriptlang.org/docs/handbook/type-compatibility.html)

View File

@@ -1,7 +1,7 @@
# Type Guards
# Type Guards / Narrowing
Type guards are a way to narrow down the type of a variable. This is useful when you want to do something different depending on the type of a variable.
Type guards and narrowing are techniques in TypeScript used to refine the type of a variable within a specific scope. They allow you to tell the TypeScript compiler that a variable is more specific than its declared type, enabling you to safely perform operations that would otherwise result in type errors. This is particularly useful when dealing with union types or situations where the initial type of a variable is broad.
Learn more from the following resources:
Visit the following resources to learn more:
- [@official@Type Guards - TypeScript Docs](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#typeof-type-guards)
- [@official@Type Guards - TypeScript Docs](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#typeof-type-guards)

View File

@@ -1,15 +1,7 @@
# Type Inference
Type inference in TypeScript refers to the process of automatically determining the type of a variable based on the value assigned to it. This allows you to write code that is more concise and easier to understand, as the TypeScript compiler can deduce the types of variables without you having to explicitly specify them.
Type inference is the automatic deduction of the data type of an expression in a programming language. Instead of explicitly declaring the type of a variable, the compiler or interpreter can infer it based on the value assigned to it or how it's used within the code. This reduces the need for verbose type annotations, making code more concise and readable while still providing the benefits of type safety.
Here's an example of type inference in TypeScript:
Visit the following resources to learn more:
```typescript
let name = 'John Doe';
```
In this example, the TypeScript compiler automatically infers that the type of the name variable is string. This means that you can use the name variable just like any other string in your code, and the TypeScript compiler will ensure that you don't perform any invalid operations on it.
Learn more from the following links:
- [@official@Type Inference](https://www.typescriptlang.org/docs/handbook/type-inference.html#handbook-content)
- [@official@Type Inference](https://www.typescriptlang.org/docs/handbook/type-inference.html#handbook-content)

View File

@@ -1,22 +1,7 @@
# Type Predicates
Type predicates are functions that return a boolean value. They are used to narrow the type of a variable. Type predicates are used in type guards.
Type predicates are a way to refine the type of a variable within a TypeScript function. They're used to tell the TypeScript compiler that a specific condition guarantees a variable is of a certain type. Instead of the compiler inferring the type based on basic checks, a type predicate explicitly asserts that if a function returns `true`, the argument must be of the specified type.
```typescript
function isString(value: unknown): value is string {
return typeof value === 'string';
}
Visit the following resources to learn more:
function example(x: unknown) {
if (isString(x)) {
// We can now call any 'string' method on 'x'.
x.toUpperCase();
} else {
console.log(x);
}
}
```
Learn more from the following links:
- [@official@Type Guards and Differentiating Types](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)
- [@official@Type Guards and Differentiating Types](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)

View File

@@ -1,17 +1,7 @@
# typeof Operator
# typeof Type Guards
The `typeof` operator is used to check the type of a variable. It returns a string value representing the type of the variable.
`typeof` in TypeScript is a way to narrow down the type of a variable based on its JavaScript `typeof` operator result. This allows you to write more precise code by checking the type of a variable (like string, number, boolean, symbol, or object) and then treating it accordingly within a specific block of code. By inspecting a variable's fundamental JavaScript type, TypeScript can infer a more specific type within that conditional block, helping catch potential errors and enabling safer operations.
```typescript
let value: string | number = 'hello';
Visit the following resources to learn more:
if (typeof value === 'string') {
console.log('value is a string');
} else {
console.log('value is a number');
}
```
Learn more from the following links:
- [@official@Type Guards and Differentiating Types](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#typeof-type-guards)
- [@official@Type Guards and Differentiating Types](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#typeof-type-guards)

View File

@@ -1,36 +1,8 @@
# Types vs Interfaces
In TypeScript, both types and interfaces can be used to define the structure of objects and enforce type checks. However, there are some differences between the two.
In TypeScript, both types and interfaces are ways to define the shape of an object. They specify what properties an object should have and the data type of those properties. Types can describe simple types like primitives (string, number, boolean) or more complex structures like unions and intersections, while interfaces are primarily used to define the structure of objects, including their properties and methods. The key difference lies in their extensibility and use cases.
Types are used to create a new named type based on an existing type or to combine existing types into a new type. They can be created using the type keyword. For example:
```typescript
type Person = {
name: string;
age: number;
};
const person: Person = {
name: 'John Doe',
age: 30,
};
```
Interfaces, on the other hand, are used to describe the structure of objects and classes. They can be created using the interface keyword. For example:
```typescript
interface Person {
name: string;
age: number;
}
const person: Person = {
name: 'John Doe',
age: 30,
};
```
Learn more from the following links:
Visit the following resources to learn more:
- [@official@Interfaces vs. Type Aliases](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces)
- [@article@Interfaces vs Types in TypeScript](https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript)
- [@article@Interfaces vs Types in TypeScript](https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript)

View File

@@ -1,23 +1,7 @@
# Functions
# TypeScript Functions
Functions are a core building block in TypeScript. Functions allow you to wrap a piece of code and reuse it multiple times. Functions in TypeScript can be either declared using function declaration syntax or function expression syntax.
Functions in TypeScript are reusable blocks of code designed to perform specific tasks. They can accept inputs (parameters), process them, and return a result. TypeScript enhances JavaScript functions by adding type annotations to parameters and return values, enabling better code clarity and error checking during development. This helps ensure that functions receive and produce the expected data types, leading to more robust and maintainable code.
> Function Declaration Syntax:
Visit the following resources to learn more:
```typescript
function name(param1: type1, param2: type2, ...): returnType {
return value;
}
```
> Function Expression Syntax:
```typescript
let name = function(param1: type1, param2: type2, ...): returnType {
return value;
};
```
Learn more from the following links:
- [@official@Functions in TypeScript](https://www.typescriptlang.org/docs/handbook/2/functions.html)
- [@official@Functions in TypeScript](https://www.typescriptlang.org/docs/handbook/2/functions.html)

View File

@@ -1,23 +1,7 @@
# Interfaces
# TypeScript Interfaces
Interfaces in TypeScript provide a way to define a contract for a type, which includes a set of properties, methods, and events. It's used to enforce a structure for an object, class, or function argument. Interfaces are not transpiled to JavaScript and are only used by TypeScript at compile-time for type-checking purposes.
Interfaces in TypeScript are a way to define a contract for the structure of an object. They describe the shape that an object should have, specifying the names, types, and optionality of its properties. Essentially, an interface names a specific combination of fields and their types. These interfaces don't compile into JavaScript; they are purely a TypeScript construct used for type-checking during development.
Here's an example of defining and using an interface in TypeScript:
Visit the following resources to learn more:
```typescript
interface User {
name: string;
age: number;
}
const user: User = {
name: 'John Doe',
age: 30,
};
```
In this example, the `User` interface defines the structure of the `user` object with two properties, `name` and `age`. The object is then typed as User using a type-assertion: `User`.
Learn more from the following links:
- [@official@TypeScript - Interfaces](https://www.typescriptlang.org/docs/handbook/2/objects.html)
- [@official@TypeScript - Interfaces](https://www.typescriptlang.org/docs/handbook/2/objects.html)

View File

@@ -1,30 +1,8 @@
# Modules
# TypeScript Modules
In TypeScript, modules are used to organize and reuse code. There are two types of modules in TypeScript:
Modules in TypeScript (and JavaScript) are a way to organize code into reusable and manageable blocks. Each module encapsulates its own variables, functions, classes, and interfaces, preventing naming collisions and promoting code modularity. Modules explicitly export parts that other code can use and import modules to gain access to their exported functionalities.
- Internal
- External
Internal modules are used to organize code within a file and are also referred to as namespaces. They are defined using the "namespace" keyword.
External modules are used to organize code across multiple files. They are defined using the "export" keyword in one file and the "import" keyword in another file. External modules in TypeScript follow the CommonJS or ES modules standards.
Here is an example of how you can use internal modules in TypeScript:
```typescript
// myModule.ts
namespace MyModule {
export function doSomething() {
console.log('Doing something...');
}
}
// main.ts
/// <reference path="myModule.ts" />
MyModule.doSomething(); // Output: "Doing something..."
```
Learn more from the following links:
Visit the following resources to learn more:
- [@official@Modules](https://www.typescriptlang.org/docs/handbook/modules.html#handbook-content)
- [@video@TypeScript - Modules](https://www.youtube.com/watch?v=EpOPR03z4Vw)
- [@video@TypeScript - Modules](https://www.youtube.com/watch?v=EpOPR03z4Vw)

View File

@@ -1,27 +1,8 @@
# Typescript Types
# TypeScript Types
TypeScript has several built-in types, including:
TypeScript Types define the kind of values a variable can hold. They essentially act as labels that specify the allowed data types, like numbers, strings, or more complex objects. By assigning types, TypeScript can perform static type checking, catching potential errors during development before the code is even run. This helps improve code reliability and makes it easier to understand how data flows through your application.
- number
- string
- boolean
- any
- void
- null and undefined
- never
- object
- symbol
- Enumerated types (enum)
- Tuple types
- Array types
- Union types
- Intersection types
- Type aliases
- Type assertions
You can also create custom types in TypeScript using interfaces, classes, and type aliases.
Learn more from the following links:
Visit the following resources to learn more:
- [@official@TypeScript - Everyday Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html)
- [@feed@Explore top posts about TypeScript](https://app.daily.dev/tags/typescript?ref=roadmapsh)
- [@feed@Explore top posts about TypeScript](https://app.daily.dev/tags/typescript?ref=roadmapsh)

View File

@@ -1,16 +1,9 @@
# TypeScript vs JavaScript
TypeScript is a superset of JavaScript that adds optional type annotations and other features such as interfaces, classes, and namespaces. JavaScript is a dynamically-typed language that is primarily used for client-side web development and can also be used for server-side development.
TypeScript and JavaScript are both programming languages used for web development. JavaScript is a dynamic language that is interpreted at runtime by the browser, meaning that type errors are only caught when the code is executed. TypeScript, on the other hand, is a superset of JavaScript that adds optional static typing. This allows developers to catch errors during development and before runtime, leading to more robust and maintainable code. TypeScript code must be compiled into JavaScript before it can be run in a browser or other JavaScript environment.
Here are a few key differences between TypeScript and JavaScript:
- **Types**: TypeScript has optional type annotations while JavaScript is dynamically-typed. This means that in TypeScript, you can specify the data type of variables, parameters, and return values, which can help catch type-related errors at compile-time.
- **Syntax**: TypeScript extends JavaScript syntax with features like interfaces, classes, and namespaces. This provides a more robust and organized structure for large-scale projects.
- **Tooling**: TypeScript has better tooling support, such as better editor integration, type checking, and code refactoring.
- **Backwards Compatibility**: TypeScript is fully compatible with existing JavaScript code, which means you can use TypeScript in any JavaScript environment.
Learn more from the following links:
Visit the following resources to learn more:
- [@official@Learning JavaScript and TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html#learning-javascript-and-typescript)
- [@article@TypeScript vs. JavaScript](https://thenewstack.io/typescript-vs-javascript/)
- [@feed@Explore top posts about JavaScript](https://app.daily.dev/tags/javascript?ref=roadmapsh)
- [@feed@Explore top posts about JavaScript](https://app.daily.dev/tags/javascript?ref=roadmapsh)

View File

@@ -1,33 +1,7 @@
# Typing Functions
In TypeScript, functions can be typed in a few different ways to indicate the input parameters and return type of the function.
Functions in programming are reusable blocks of code that perform specific tasks. Typing functions in TypeScript means defining the types of the parameters a function accepts and the type of value it returns. This allows the TypeScript compiler to verify that functions are used correctly, preventing type-related errors at runtime and enhancing code maintainability and readability.
Function declaration with types:
Visit the following resources to learn more:
```typescript
function add(a: number, b: number): number {
return a + b;
}
```
Arrow function with types:
```typescript
const multiply = (a: number, b: number): number => {
return a * b;
};
```
Function type:
```typescript
let divide: (a: number, b: number) => number;
divide = (a, b) => {
return a / b;
};
```
Learn more from the following links:
- [@official@TypeScript Functions](https://www.typescriptlang.org/docs/handbook/2/functions.html)
- [@official@TypeScript Functions](https://www.typescriptlang.org/docs/handbook/2/functions.html)

View File

@@ -8,16 +8,14 @@ With `strictNullChecks` off, values that might be `null` or `undefined` can stil
With `strictNullChecks` on, when a value is `null` or `undefined`, you will need to test for those values before using methods or properties on that value. Just like checking for `undefined` before using an optional property, we can use narrowing to check for values that might be `null`:
```typescript
function doSomething(x: string | null) {
if (x === null) {
// do nothing
} else {
console.log('Hello, ' + x.toUpperCase());
}
}
```
function doSomething(x: string | null) {
if (x === null) {
// do nothing
} else {
console.log('Hello, ' + x.toUpperCase());
}
}
Learn more from the following links:
Visit the following resources to learn more:
- [@official@null and undefined](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined)
- [@official@null and undefined](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined)

View File

@@ -1,15 +1,7 @@
# Union Types
Union Types in TypeScript allow you to specify multiple possible types for a single variable or parameter. A union type is written as a vertical bar `|` separated list of types.
Union types allow a variable to hold values of different types. This means you can specify that a variable can be, for example, either a `string` or a `number`. You define a union type using the pipe (`|`) symbol to separate the possible types. This provides flexibility in situations where a variable might accept multiple different data types.
For example, consider a function that takes either a string or a number as an argument:
Visit the following resources to learn more:
```typescript
function combine(input1: string | number, input2: string | number) {
return input1 + input2;
}
```
Learn more from the following links:
- [@official@Union Types in TypeScript](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types)
- [@official@Union Types in TypeScript](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types)

View File

@@ -1,18 +1,7 @@
# Unknown
# Unknown Type
`unknown` is the type-safe counterpart of any. Anything is assignable to `unknown`, but `unknown` isnt assignable to anything but itself and `any` without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an `unknown` without first asserting or narrowing to a more specific type.
The `unknown` type in TypeScript represents a value that can be anything. Unlike `any`, which essentially disables type checking, `unknown` forces you to perform type checks or type assertions before you can perform operations on a value declared as `unknown`. This helps prevent unexpected errors at runtime by ensuring you've handled the potential type of the value.
```typescript
function f1(a: any) {
a.b(); // OK
}
Visit the following resources to learn more:
function f2(a: unknown) {
// Error: Property 'b' does not exist on type 'unknown'.
a.b();
}
```
Learn more from the following links:
- [@official@Unknown Type in TypeScript](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type)
- [@official@Unknown Type in TypeScript](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type)

View File

@@ -1,11 +1,11 @@
# Useful Packages
TypeScript has a large ecosystem of packages that can be used to extend the language or to add functionality to your project. Here is the list of some of the most useful packages.
TypeScript has a large ecosystem of packages that can be used to extend the language or to add functionality to your project.
- [@article@zod](https://zod.dev/): A TypeScript-first data validation library
- [@opensource@ts-morph](https://github.com/dsherret/ts-morph): A TypeScript-first API for manipulating TypeScript code
- [@article@ts-node](https://typestrong.org/ts-node/): A TypeScript execution and REPL for node.js
- [@opensource@ts-jest](https://github.com/kulshekhar/ts-jest): A Jest transformer with source map support that lets you use Jest to test projects written in TypeScript.
- [@opensource@typesync](https://github.com/jeffijoe/typesync): Install missing TypeScript typings for dependencies in your package.json.
- [@opensource@tsd](https://github.com/SamVerschueren/tsd) - TypeScript Definition Manager
- [@opensource@type-fest](https://github.com/sindresorhus/type-fest) - A collection of essential TypeScript types
Visit the following resources to learn more:
- [@official@zod](https://zod.dev/)
- [@official@ts-node](https://typestrong.org/ts-node)
- [@opensource@ts-morph](https://github.com/dsherret/ts-morph)
- [@opensource@ts-jest](https://github.com/kulshekhar/ts-jest)
- [@opensource@typesync](https://github.com/jeffijoe/typesync)

View File

@@ -1,15 +1,8 @@
# Utility Types
TypeScript provides several utility types that can be used to manipulate and transform existing types. Here are some of the most common ones:
Utility Types in TypeScript are built-in generic types that perform common type transformations. They allow you to create new types based on existing ones by applying operations like making properties optional, required, readonly, or picking specific properties. These utilities enhance type safety and code reusability by enabling you to express complex type manipulations in a concise and declarative way.
- `Partial`: makes all properties of a type optional.
- `Readonly`: makes all properties of a type read-only.
- `Pick`: allows you to pick specific properties from a type.
- `Omit`: allows you to omit specific properties from a type.
- `Exclude`: creates a type that is the set difference of A and B.
- ..and more.
Learn more from the following links:
Visit the following resources to learn more:
- [@official@TypeScript - Utility Types](https://www.typescriptlang.org/docs/handbook/utility-types.html)
- [@article@TypeScript Utility Types Guide](https://camchenry.com/blog/typescript-utility-types)
- [@article@TypeScript Utility Types Guide](https://camchenry.com/blog/typescript-utility-types)

View File

@@ -1,16 +1,7 @@
# void
# Void Type
`void` represents the return value of functions which dont return a value. Its the inferred type any time a function doesnt have any `return` statements, or doesnt return any explicit value from those return statements:
The `void` type in TypeScript represents the absence of a value. It is commonly used as the return type of functions that do not return any value, essentially indicating that the function performs an action but doesn't produce a result. A function declared with a `void` return type is not expected to return any data back to the caller.
```typescript
// The inferred return type is void
function noop() {
return;
}
```
Visit the following resources to learn more:
In JavaScript, a function that doesnt return any value will implicitly return the value `undefined`. However, `void` and `undefined` are not the same thing in TypeScript. There are further details at the end of this chapter.
Learn more from the following links:
- [@official@void - TypeScript Docs](https://www.typescriptlang.org/docs/handbook/2/functions.html#void)
- [@official@void - TypeScript Docs](https://www.typescriptlang.org/docs/handbook/2/functions.html#void)