Add content to TypeScript roadmap

pull/3423/head
Kamran Ahmed 2 years ago
parent a4dddfb19b
commit 659bd93094
  1. 10
      src/roadmaps/typescript/content/100-typescript/100-typescript-vs-javascript.md
  2. 2
      src/roadmaps/typescript/content/100-typescript/101-ts-js-interoperability.md
  3. 19
      src/roadmaps/typescript/content/100-typescript/102-install-configure/100-tsconfig-json.md
  4. 27
      src/roadmaps/typescript/content/100-typescript/102-install-configure/101-compiler-options.md
  5. 66
      src/roadmaps/typescript/content/100-typescript/102-install-configure/index.md
  6. 14
      src/roadmaps/typescript/content/100-typescript/103-running-typescript/100-tsc.md
  7. 8
      src/roadmaps/typescript/content/100-typescript/103-running-typescript/101-ts-node.md
  8. 4
      src/roadmaps/typescript/content/100-typescript/103-running-typescript/102-ts-playground.md
  9. 23
      src/roadmaps/typescript/content/100-typescript/103-running-typescript/index.md
  10. 3
      src/roadmaps/typescript/content/100-typescript/index.md
  11. 16
      src/roadmaps/typescript/content/101-typescript-types/100-boolean.md
  12. 16
      src/roadmaps/typescript/content/101-typescript-types/101-number.md
  13. 14
      src/roadmaps/typescript/content/101-typescript-types/102-string.md
  14. 22
      src/roadmaps/typescript/content/101-typescript-types/103-void.md
  15. 27
      src/roadmaps/typescript/content/101-typescript-types/104-undefined.md
  16. 24
      src/roadmaps/typescript/content/101-typescript-types/105-null.md
  17. 19
      src/roadmaps/typescript/content/101-typescript-types/106-interface.md
  18. 32
      src/roadmaps/typescript/content/101-typescript-types/107-class.md
  19. 22
      src/roadmaps/typescript/content/101-typescript-types/108-enum.md
  20. 6
      src/roadmaps/typescript/content/101-typescript-types/109-array.md
  21. 14
      src/roadmaps/typescript/content/101-typescript-types/110-tuple.md
  22. 28
      src/roadmaps/typescript/content/101-typescript-types/111-any.md
  23. 22
      src/roadmaps/typescript/content/101-typescript-types/112-object.md
  24. 23
      src/roadmaps/typescript/content/101-typescript-types/113-unknown.md
  25. 36
      src/roadmaps/typescript/content/101-typescript-types/114-never.md
  26. 18
      src/roadmaps/typescript/content/101-typescript-types/115-type-assertions/index.md
  27. 68
      src/roadmaps/typescript/content/101-typescript-types/116-satisfies-keyword.md
  28. 32
      src/roadmaps/typescript/content/101-typescript-types/index.md
  29. 3
      src/roadmaps/typescript/content/102-type-inference.md
  30. 21
      src/roadmaps/typescript/content/103-type-compatibility.md
  31. 15
      src/roadmaps/typescript/content/104-combining-types/100-union-types.md
  32. 23
      src/roadmaps/typescript/content/104-combining-types/101-intersection-types.md
  33. 13
      src/roadmaps/typescript/content/104-combining-types/102-type-aliases.md
  34. 24
      src/roadmaps/typescript/content/104-combining-types/103-keyof-operator.md
  35. 45
      src/roadmaps/typescript/content/104-combining-types/index.md
  36. 18
      src/roadmaps/typescript/content/105-type-guards/100-typeof-operator.md
  37. 28
      src/roadmaps/typescript/content/105-type-guards/101-instanceof-operator.md
  38. 21
      src/roadmaps/typescript/content/105-type-guards/102-equality.md
  39. 18
      src/roadmaps/typescript/content/105-type-guards/103-truthiness.md
  40. 23
      src/roadmaps/typescript/content/105-type-guards/104-type-predicates.md
  41. 8
      src/roadmaps/typescript/content/105-type-guards/index.md
  42. 42
      src/roadmaps/typescript/content/106-functions/100-typing-functions.md
  43. 21
      src/roadmaps/typescript/content/106-functions/101-function-overloading.md
  44. 50
      src/roadmaps/typescript/content/106-functions/index.md
  45. 44
      src/roadmaps/typescript/content/107-interfaces/100-types-vs-interfaces.md
  46. 35
      src/roadmaps/typescript/content/107-interfaces/101-extending-interfaces.md
  47. 22
      src/roadmaps/typescript/content/107-interfaces/102-interface-declaration.md
  48. 36
      src/roadmaps/typescript/content/107-interfaces/103-hybrid-types.md
  49. 25
      src/roadmaps/typescript/content/107-interfaces/index.md
  50. 13
      src/roadmaps/typescript/content/108-classes/100-constructor-params.md
  51. 33
      src/roadmaps/typescript/content/108-classes/101-constructor-overloading.md
  52. 8
      src/roadmaps/typescript/content/108-classes/102-access-modifiers.md
  53. 8
      src/roadmaps/typescript/content/108-classes/103-abstract-classes.md
  54. 54
      src/roadmaps/typescript/content/108-classes/104-inheritance-vs-polymorphism.md
  55. 39
      src/roadmaps/typescript/content/108-classes/105-method-overriding.md
  56. 32
      src/roadmaps/typescript/content/108-classes/index.md
  57. 35
      src/roadmaps/typescript/content/109-generics/100-generic-types.md
  58. 27
      src/roadmaps/typescript/content/109-generics/101-generic-constraints.md
  59. 13
      src/roadmaps/typescript/content/109-generics/index.md
  60. 46
      src/roadmaps/typescript/content/110-decorators.md
  61. 41
      src/roadmaps/typescript/content/111-utility-types/100-partial.md
  62. 32
      src/roadmaps/typescript/content/111-utility-types/101-pick.md
  63. 55
      src/roadmaps/typescript/content/111-utility-types/102-omit.md
  64. 20
      src/roadmaps/typescript/content/111-utility-types/103-readonly.md
  65. 32
      src/roadmaps/typescript/content/111-utility-types/104-record.md
  66. 16
      src/roadmaps/typescript/content/111-utility-types/105-exclude.md
  67. 12
      src/roadmaps/typescript/content/111-utility-types/106-extract.md
  68. 15
      src/roadmaps/typescript/content/111-utility-types/107-non-nullable.md
  69. 59
      src/roadmaps/typescript/content/111-utility-types/108-parameters.md
  70. 54
      src/roadmaps/typescript/content/111-utility-types/109-return-type.md
  71. 39
      src/roadmaps/typescript/content/111-utility-types/110-instance-type.md
  72. 21
      src/roadmaps/typescript/content/111-utility-types/111-awaited.md
  73. 11
      src/roadmaps/typescript/content/111-utility-types/index.md
  74. 3
      src/roadmaps/typescript/content/112-advanced-types/100-mapped-types.md
  75. 2
      src/roadmaps/typescript/content/112-advanced-types/101-conditional-types.md
  76. 3
      src/roadmaps/typescript/content/112-advanced-types/102-literal-types.md
  77. 11
      src/roadmaps/typescript/content/112-advanced-types/103-template-literal-types.md
  78. 8
      src/roadmaps/typescript/content/112-advanced-types/104-recursive-types.md
  79. 20
      src/roadmaps/typescript/content/113-modules/100-namespaces.md
  80. 19
      src/roadmaps/typescript/content/113-modules/101-ambient-modules.md
  81. 18
      src/roadmaps/typescript/content/113-modules/102-external-modules.md
  82. 38
      src/roadmaps/typescript/content/113-modules/103-namespace-augmentation.md
  83. 30
      src/roadmaps/typescript/content/113-modules/104-global-augmentation.md
  84. 20
      src/roadmaps/typescript/content/113-modules/index.md
  85. 20
      src/roadmaps/typescript/content/114-ecosystem/100-formatting.md
  86. 33
      src/roadmaps/typescript/content/114-ecosystem/101-linting.md
  87. 56
      src/roadmaps/typescript/content/114-ecosystem/102-useful-packages.md
  88. 19
      src/roadmaps/typescript/content/114-ecosystem/103-build-tools.md
  89. 23
      src/roadmaps/typescript/content/114-ecosystem/index.md

@ -4,13 +4,11 @@ TypeScript is a superset of JavaScript that adds optional type annotations and o
Here are a few key differences between TypeScript and JavaScript: Here are a few key differences between TypeScript and JavaScript:
1. 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. - **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.
2. Syntax: TypeScript extends JavaScript syntax with features like interfaces, classes, and namespaces. This provides a more robust and organized structure for large-scale projects. - **Syntax**: TypeScript extends JavaScript syntax with features like interfaces, classes, and namespaces. This provides a more robust and organized structure for large-scale projects.
3. Tooling: TypeScript has better tooling support, such as better editor integration, type checking, and code refactoring. - **Tooling**: TypeScript has better tooling support, such as better editor integration, type checking, and code refactoring.
4. Backwards Compatibility: TypeScript is fully compatible with existing JavaScript code, which means you can use TypeScript in any JavaScript environment. - **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: Learn more from the following links:
- [Learning JavaScript and TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html#learning-javascript-and-typescript) - [Learning JavaScript and TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html#learning-javascript-and-typescript)
- [Difference between TypeScript and JavaScript](https://www.geeksforgeeks.org/difference-between-typescript-and-javascript/)
- [JavaScript vs TypeScript | Full Stack Course](https://www.youtube.com/watch?v=DxcpvaDglb4)

@ -1,4 +1,4 @@
# TS JS Interoperability # TS/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 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.

@ -1,17 +1,17 @@
# Tsconfig JSON # 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 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:
- **target**: the version of JavaScript to compile to. - `target`: the version of JavaScript to compile to.
- **module**: the module system to use. - `module`: the module system to use.
- **stric**": enables/disables strict type checking. - `strict`: enables/disables strict type checking.
- **outDir**: the directory to output the compiled JavaScript files. - `outDir`: the directory to output the compiled JavaScript files.
- **rootDir**: the root directory of the TypeScript files. - `rootDir`: the root directory of the TypeScript files.
- **exclude**: an array of file/directory patterns to exclude from the compilation. - `exclude`: an array of file/directory patterns to exclude from the compilation.
Example: Given below is the sample `tsconfig.json` file:
``` ```json
{ {
"compilerOptions": { "compilerOptions": {
"target": "es5", "target": "es5",
@ -27,4 +27,3 @@ Example:
Learn more from the following links: Learn more from the following links:
- [What is a tsconfig.json](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#handbook-content) - [What is a tsconfig.json](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#handbook-content)
- [TypeScript Projects: What is a tsconfig.json?](https://www.youtube.com/watch?v=sLylejlr6lA)

@ -1,30 +1,11 @@
# Compiler Options # Compiler Options
Compiler options in TypeScript are a set of configuration settings that control how the TypeScript compiler compiles your code. Here are some commonly used compiler options with examples: 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:
1. target ```bash
2. module tsc --target ES5 --module commonjs
3. strict
4. outDir
5. rootDir
6. exclude
Have a look at the following example tsconfig.json:
```
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src",
"exclude": ["node_modules"]
}
}
``` ```
Learn more from the following links: Learn more from the following links:
- [Compiler Options](https://www.typescriptlang.org/docs/handbook/compiler-options.html#compiler-options) - [Compiler Options](https://www.typescriptlang.org/docs/handbook/compiler-options.html)
- [TypeScript Compiler Options](https://www.youtube.com/watch?v=I1ZFsPK0Q-Y&vl=en)

@ -1,56 +1,48 @@
# Install Configure # Install and Configure
To install and configure TypeScript in your project, you need to perform the following steps: To install and configure TypeScript in your project, you need to perform the following steps:
- Install TypeScript globally on your machine using npm (Node Package Manager):
```
npm install -g typescript
```
- Initialize npm in your project directory by running the following command: - Initialize npm in your project directory by running the following command:
``` ```bash
npm init npm init
``` ```
- Install TypeScript as a project dependency by running the following command: - Install TypeScript as a project dependency by running the following command:
``` ```bash
npm install --save-dev typescript 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: - Create a `tsconfig.json` file in your project directory to specify the compiler options for building your project. For example:
``` ```json
{ {
"compilerOptions": { "compilerOptions": {
"target": "es5", "target": "es5",
"module": "commonjs", "module": "commonjs",
"strict": true, "strict": true,
"outDir": "./dist", "outDir": "./dist",
"rootDir": "./src", "rootDir": "./src",
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
} }
``` ```
- Compile your TypeScript code using the following command: - Compile your TypeScript code using the following command:
``` ```bash
tsc tsc
``` ```
Note: You can also compile individual TypeScript files by specifying the file name after the tsc command.For example: Note: You can also compile individual TypeScript files by specifying the file name after the tsc command.For example:
``` ```bash
tsc index.ts tsc index.ts
``` ```
And you're all set! You can now start writing TypeScript code in your project. And you're all set! You can now start writing TypeScript code in your project.
Learn more from the following links: Learn more from the following links:
- [How To Configure TypeScript](https://www.youtube.com/watch?v=SEnAS_ooHeA) - [Install and Configure TypeScript](https://www.typescriptlang.org/download)
- [Installing TypeScript](https://www.typescriptlang.org/download)

@ -1,18 +1,18 @@
# Tsc # 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 tool for the TypeScript compiler. It compiles TypeScript code into JavaScript code, making it compatible with the browser or any JavaScript runtime environment.
You can use the `tsc` command to compile your TypeScript code by running the following command in your terminal or command prompt: You can use the `tsc` command to compile your TypeScript code by running the following command in your terminal or command prompt:
``` ```bash
tsc 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: 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 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. 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.

@ -1,8 +1,6 @@
# Ts Node # ts-node
TypeScript is a statically-typed language that can be used with the Flutter framework to build cross-platform mobile apps. TypeScript offers features such as type checking, classes, interfaces, and more, which can help improve the development process and catch errors early. It can be used in Flutter by integrating it with the Dart programming language through a tool called dart2ts. This allows developers to use TypeScript with Flutter and take advantage of its benefits while still using Dart for the underlying runtime. ts-node is a TypeScript execution and REPL for node.js, with source map and native ESM support. Learn more from the following links:
Learn more from the following links: - [ts-node - GitHub Project](https://github.com/TypeStrong/ts-node)
- [TypeScript Node Explained *ts-node*](https://www.youtube.com/watch?v=22MpfOmemzY)
- [How To Run TypeScript Scripts with ts-node](https://www.digitalocean.com/community/tutorials/typescript-running-typescript-ts-node) - [How To Run TypeScript Scripts with ts-node](https://www.digitalocean.com/community/tutorials/typescript-running-typescript-ts-node)

@ -1,6 +1,6 @@
# Ts playground # TS Playground
A TypeScript playground in Flutter refers to a development environment or an online tool that allows you to write, run, and debug TypeScript code in a Flutter environment. It's a way to test TypeScript code snippets and see the results immediately, without having to set up a full development environment or project. Some popular online TypeScript playgrounds for Flutter include Repl.it, CodeSandbox, and StackBlitz. These platforms provide an interactive development environment with all the necessary tools and features to write, test, and debug TypeScript code. 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.
Learn more from the following links: Learn more from the following links:

@ -2,16 +2,19 @@
To run TypeScript code, you'll need to have a TypeScript compiler installed. Here's a general process to run TypeScript code: To run TypeScript code, you'll need to have a TypeScript compiler installed. Here's a general process to run TypeScript code:
1. Write TypeScript code in a .ts file (e.g. app.ts) - Write TypeScript code in a `.ts` file (e.g. `app.ts`)
2. Compile the TypeScript code into JavaScript using the TypeScript compiler: - Compile the TypeScript code into JavaScript using the TypeScript compiler:
```
tsc app.ts ```bash
``` tsc app.ts
3. Run the generated JavaScript code using a JavaScript runtime environment such as Node.js: ```
```
node app.js - Run the generated JavaScript code using a JavaScript runtime environment such as Node.js:
```
```bash
node app.js
```
Learn more from the following link: Learn more from the following link:
- [Running your TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-tooling-in-5-minutes.html#running-your-typescript-web-app) - [Running your TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-tooling-in-5-minutes.html)

@ -12,5 +12,4 @@ The main benefits of using TypeScript include:
Learn more from the folowing links: Learn more from the folowing links:
- [Overview of TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html) - [Overview of TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html)
- [TypeScript: A Static Type Checker](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html#typescript-a-static-type-checker) - [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html)
- [Learn Complete TypeScript](https://www.youtube.com/watch?v=30LWjhZzg50)

@ -1,14 +1,12 @@
# Boolean # boolean
`boolean` is a primitive data type in TypeScript that represents a truth value, either true or false. `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:
For example: ```typescript
let isTrue: boolean = true;
``` let isFalse: boolean = false;
let isTrue: boolean = true; ```
let isFalse: boolean = false;
```
Learn more from the following links: Learn more from the following links:
- [Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#number-string-boolean-symbol-and-object) - [Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean)

@ -1,16 +1,12 @@
# Number # number
It is a primitive data type in TypeScript that represents numeric values. It includes both integer and floating-point values. It is a primitive data type in TypeScript that represents numeric values. It includes both integer and floating-point values.
For example: ```typescript
let intValue: number = 42;
``` let floatValue: number = 3.14;
let intValue: number = 42; ```
let floatValue: number = 3.14;
```
In TypeScript, numbers can be assigned to variables, passed as arguments to functions, and returned from functions. They are also compatible with arithmetic operators such as +, -, *, /, and % (modulus).
Learn more from the following links: Learn more from the following links:
- [Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#number-string-boolean-symbol-and-object) - [Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean)

@ -1,13 +1,11 @@
# String # string
In TypeScript, the string is sequence of char values and also considered as an object. 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.
Syntax: ```typescript
let name: string = 'John Doe';
```
var var_name = new String(string);
``` ```
Learn more from the following links: Learn more from the following link
- [Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#number-string-boolean-symbol-and-object) - [Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean)

@ -1,18 +1,18 @@
# Void # void
Void is used where there is no data. For example, if a function does not return any value then you can specify void as return type. `void` represents the return value of functions which don’t return a value. It’s the inferred type any time a function doesn’t have any `return` statements, or doesn’t return any explicit value from those return statements:
Example:
``` ```typescript
function sayHi(): void { // The inferred return type is void
console.log('Hi!') function noop() {
} return;
}
```
In JavaScript, a function that doesn’t 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.
let speech: void = sayHi();
console.log(speech); //Output: undefined
```
Learn more from the following links: Learn more from the following links:
- [void](https://www.typescriptlang.org/docs/handbook/2/functions.html#void) - [void - TypeScript Docs](https://www.typescriptlang.org/docs/handbook/2/functions.html#void)

@ -1,19 +1,22 @@
# Undefined # undefined
In TypeScript, undefined is a built-in type that represents the absence of a value. It can be assigned to variables, properties, or function return values when there is no meaningful value to return. JavaScript has two primitive values used to signal absent or uninitialized value: `null` (absent) and `undefined` (unintialized).
For example: TypeScript has two corresponding *types* by the same names. How these types behave depends on whether you have the `strictNullChecks` option on.
``` 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 it’s practical to do so in the codebase.
let x: undefined;
x = undefined; // valid
x = null; // not valid
function doSomething(): undefined { 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`:
// ...
return undefined; ```typescript
} function doSomething(x: string | null) {
``` if (x === null) {
// do nothing
} else {
console.log("Hello, " + x.toUpperCase());
}
}
```
Learn more from the following links: Learn more from the following links:

@ -1,13 +1,23 @@
# Null # null
In TypeScript, both undefined and null actually have their types named undefined and null respectively. Much like void, they’re not extremely useful on their own: JavaScript has two primitive values used to signal absent or uninitialized value: `null` (absent) and `undefined` (unintialized).
``` TypeScript has two corresponding *types* by the same names. How these types behave depends on whether you have the `strictNullChecks` option on.
// Not much else we can assign to these variables!
let u: undefined = undefined; 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 it’s practical to do so in the codebase.
let n: null = null;
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: Learn more from the following links:
- [Null and Undefined](https://www.typescriptlang.org/docs/handbook/basic-types.html#null-and-undefined) - [null and undefined](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined)

@ -2,16 +2,17 @@
TypeScript allows you to specifically type an object using an interface that can be reused by multiple objects. TypeScript allows you to specifically type an object using an interface that can be reused by multiple objects.
Example: ```typescript
interface Person {
name: string;
age: number;
}
``` function greet(person: Person) {
interface Publication { return 'Hello ' + person.name;
isbn: string; }
author: string; ```
publisher: string;
}
```
Learn more from the following links: Learn more from the following links:
- [Reusable Types (Interfaces)](https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html#reusable-types-interfaces) - [Object Types - Interfaces](https://www.typescriptlang.org/docs/handbook/2/objects.html)

@ -2,24 +2,24 @@
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: 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:
``` ```typescript
class Car { class Car {
make: string; make: string;
model: string; model: string;
year: number; year: number;
constructor(make: string, model: string, year: number) { constructor(make: string, model: string, year: number) {
this.make = make; this.make = make;
this.model = model; this.model = model;
this.year = year; this.year = year;
} }
drive() { drive() {
console.log(`Driving my ${this.year} ${this.make} ${this.model}`); console.log(`Driving my ${this.year} ${this.make} ${this.model}`);
} }
} }
``` ```
Learn more from the following links: Learn more from the following links:
- [Classes](https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html#classes) - [TypeScript Classes](https://www.typescriptlang.org/docs/handbook/2/classes.html)

@ -2,16 +2,20 @@
Enums is not a type-level extension of JavaScript. It allow 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. Enums is not a type-level extension of JavaScript. It allow 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.
Example: Here is an example of a numeric enum in TypeScript:
``` ```typescript
enum Direction { enum Direction {
Up = 1, Up = 1,
Down, Down,
Left, Left,
Right, 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: Learn more from the following links:

@ -1,6 +1,10 @@
# Array # 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. We’ll learn more about the syntax T<U> when we cover generics. 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.
```typescript
const numbers: number[] = [1, 2, 3];
```
Learn more from the following links: Learn more from the following links:

@ -2,9 +2,17 @@
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 type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions.
``` ```typescript
type StringNumberPair = [string, number]; type StringNumberPair = [string, number];
```
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: Learn more from the following links:

@ -1,19 +1,21 @@
# Any # Any
With `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 that’s syntactically legal: TypeScript has a special type, `any`, that you can use whenever you don’t want a particular value to cause typechecking errors.
``` 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 that’s syntactically legal:
let obj: any = { x: 0 };
// None of the following lines of code will throw compiler errors. ```typescript
// Using `any` disables all further type checking, and it is assumed let obj: any = { x: 0 };
// you know the environment better than TypeScript. // None of the following lines of code will throw compiler errors.
obj.foo(); // Using `any` disables all further type checking, and it is assumed
obj(); // you know the environment better than TypeScript.
obj.bar = 100; obj.foo();
obj = "hello"; obj();
const n: number = obj; obj.bar = 100;
``` obj = "hello";
const n: number = obj;
```
Learn more from the following links: Learn more from the following links:
- [any](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any) - [any type in TypeScript](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any)

@ -1,19 +1,19 @@
# Object # Object
To define an object type, we simply list its properties and their types. To define an `object` type, we simply list its properties and their types.
For example, here’s a function that takes a point-like object: For example, here’s a function that takes a point-like object:
``` ```typescript
// The parameter's type annotation is an object type // The parameter's type annotation is an object type
function printCoord(pt: { x: number; y: number }) { function printCoord(pt: { x: number; y: number }) {
console.log("The coordinate's x value is " + pt.x); console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y); console.log("The coordinate's y value is " + pt.y);
} }
printCoord({ x: 3, y: 7 });
``` printCoord({ x: 3, y: 7 });
```
Learn more from the following links: Learn more from the following links:
- [Number, String, Boolean, Symbol and Object](https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#number-string-boolean-symbol-and-object) - [Object Types in TypeScript](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#object-types)
- [Object Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#object-types)

@ -1,19 +1,18 @@
# Unknown # Unknown
The unknown type represents any value. This is similar to the any type, but is safer because it’s not legal to do anything with an unknown value: `unknown` is the type-safe counterpart of any. Anything is assignable to `unknown`, but `unknown` isn’t 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.
``` ```typescript
function f1(a: any) { function f1(a: any) {
a.b(); // OK a.b(); // OK
} }
function f2(a: unknown) {
a.b();
Object is of type 'unknown'.
}
```
This is useful when describing function types because you can describe functions that accept any value without having any values in your function body. function f2(a: unknown) {
// Error: Property 'b' does not exist on type 'unknown'.
a.b();
}
```
Learn more from the following links: Learn more from the following links:
- [Unknown](https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown) - [Unknown Type in TypeScript](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type)

@ -1,27 +1,27 @@
# Never # Never
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 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 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 isn’t assignable to never. 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 isn’t assignable to `never`.
Examples of functions returning never: Examples of functions returning never:
``` ```typescript
// Function returning never must not have a reachable end point // Function returning never must not have a reachable end point
function error(message: string): never { function error(message: string): never {
throw new Error(message); throw new Error(message);
} }
// Inferred return type is never // Inferred return type is never
function fail() { function fail() {
return error("Something failed"); return error("Something failed");
} }
// Function returning never must not have a reachable end point // Function returning never must not have a reachable end point
function infiniteLoop(): never { function infiniteLoop(): never {
while (true) {} while (true) {}
} }
``` ```
Learn more from the following links: Learn more from the following links:

@ -4,20 +4,20 @@ Type assertions in TypeScript are a way to tell the compiler to treat a value as
There are two syntaxes for type assertions in TypeScript: There are two syntaxes for type assertions in TypeScript:
1. The "angle-bracket" syntax: `<T>value` - The "angle-bracket" syntax: `<T>value`
2. The "as" syntax: value as `T` - The "as" syntax: value as `T`
For example: For example:
``` ```typescript
let num = 42; let num = 42;
// using angle-bracket syntax // using angle-bracket syntax
let str = <string>num; let str = <string>num;
// using as syntax // using as syntax
let str2 = num as string; let str2 = num as string;
``` ```
In both examples, `num` is a number, but the type assertions tell the compiler to treat the value as a string. In both examples, `num` is a number, but the type assertions tell the compiler to treat the value as a string.

@ -1,23 +1,59 @@
# Satisfies Keyword # satisfies Keyword
TypeScript developers are often faced with a dilemma: we want to ensure that some expression matches some type, but also want to keep the most specific type of that expression for inference purposes. TypeScript developers are often faced with a dilemma: we want to ensure that some expression matches some type, but also want to keep the most specific type of that expression for inference purposes.
For example: For example:
``` ```typescript
// Each property can be a string or an RGB tuple. // Each property can be a string or an RGB tuple.
const palette = { const palette = {
red: [255, 0, 0], red: [255, 0, 0],
green: "#00ff00", green: "#00ff00",
bleu: [0, 0, 255] bleu: [0, 0, 255]
// ^^^^ sacrebleu - we've made a typo! // ^^^^ sacrebleu - we've made a typo!
}; };
// We want to be able to use array methods on 'red'...
const redComponent = palette.red.at(0); // We want to be able to use array methods on 'red'...
// or string methods on 'green'... const redComponent = palette.red.at(0);
const greenNormalized = palette.green.toUpperCase();
``` // or string methods on 'green'...
const greenNormalized = palette.green.toUpperCase();
Learn more from the following links: ```
Notice that we’ve written `bleu`, whereas we probably should have written `blue`. We could try to catch that `bleu` typo by using a type annotation on palette, but we’d lose the information about each property.
```typescript
type Colors = "red" | "green" | "blue";
type RGB = [red: number, green: number, blue: number];
const palette: Record<Colors, string | RGB> = {
red: [255, 0, 0],
green: "#00ff00",
bleu: [0, 0, 255]
// ~~~~ The typo is now correctly detected
};
// But we now have an undesirable error here - 'palette.red' "could" be a string.
const redComponent = palette.red.at(0);
```
The `satisfies` operator lets us validate that the type of an expression matches some type, without changing the resulting type of that expression. As an example, we could use `satisfies` to validate that all the properties of palette are compatible with `string | number[]`:
```typescript
type Colors = "red" | "green" | "blue";
type RGB = [red: number, green: number, blue: number];
const palette = {
red: [255, 0, 0],
green: "#00ff00",
bleu: [0, 0, 255]
// ~~~~ The typo is now caught!
} satisfies Record<Colors, string | RGB>;
// Both of these methods are still accessible!
const redComponent = palette.red.at(0);
const greenNormalized = palette.green.toUpperCase();
```
Learn more from the following resources:
- [Satisfies Keyword](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator) - [Satisfies Keyword](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator)

@ -2,22 +2,22 @@
TypeScript has several built-in types, including: TypeScript has several built-in types, including:
1. number - number
2. string - string
3. boolean - boolean
4. any - any
5. void - void
6. null and undefined - null and undefined
7. never - never
8. object - object
9. symbol - symbol
10. Enumerated types (enum) - Enumerated types (enum)
11. Tuple types - Tuple types
12. Array types - Array types
13. Union types - Union types
14. Intersection types - Intersection types
15. Type aliases - Type aliases
16. Type assertions - Type assertions
You can also create custom types in TypeScript using interfaces, classes, and type aliases. You can also create custom types in TypeScript using interfaces, classes, and type aliases.

@ -4,7 +4,7 @@ Type inference in TypeScript refers to the process of automatically determining
Here's an example of type inference in TypeScript: Here's an example of type inference in TypeScript:
``` ```typescript
let name = "John Doe"; let name = "John Doe";
``` ```
@ -13,4 +13,3 @@ In this example, the TypeScript compiler automatically infers that the type of t
Learn more from the following links: Learn more from the following links:
- [Type Inference](https://www.typescriptlang.org/docs/handbook/type-inference.html#handbook-content) - [Type Inference](https://www.typescriptlang.org/docs/handbook/type-inference.html#handbook-content)
- [Type Inference in TypeScript](https://www.tutorialsteacher.com/typescript/type-inference)

@ -1,24 +1,23 @@
# Type Compatibility # Type Compatibility
Type compatibility in TypeScript refers to the compatibility between different types in TypeScript. TypeScript uses structural typing to determine type compatibility. This means that two types are considered compatible if they have the same structure, regardless of their names. TypeScript uses structural typing to determine type compatibility. This means that two types are considered compatible if they have the same structure, regardless of their names.
Here's an example of type compatibility in TypeScript: Here's an example of type compatibility in TypeScript:
``` ```typescript
interface Point { interface Point {
x: number; x: number;
y: number; y: number;
} }
let p1: Point = { x: 10, y: 20 }; let p1: Point = { x: 10, y: 20 };
let p2: { x: number; y: number } = p1; let p2: { x: number; y: number } = p1;
console.log(p2.x); // Output: 10 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. 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: Learn more from the following links:
- [Type Compatibility](https://www.typescriptlang.org/docs/handbook/type-compatibility.html) - [Type Compatibility](https://www.typescriptlang.org/docs/handbook/type-compatibility.html)
- [Tutorial - Type Compatibility in TypeScript](youtube.com/watch?v=wqm5ibtCSf0)

@ -1,16 +1,15 @@
# Union Types # 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 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.
For example, consider a function that takes either a string or a number as an argument: For example, consider a function that takes either a string or a number as an argument:
``` ```typescript
function combine(input1: string | number, input2: string | number) { function combine(input1: string | number, input2: string | number) {
return input1 + input2; return input1 + input2;
} }
``` ```
Learn more from the following links: Learn more from the following links:
- [Unions Types](https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html) - [Union Types in TypeScript](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types)
- [Union Types in TypeScript](https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html)

@ -1,22 +1,17 @@
# Intersection Types # Intersection Types
Intersection Types in TypeScript allow you to combine multiple types into a single type. An intersection type is written as an ampersand (&) separated list of types. An intersection type creates a new type by combining multiple existing types. The new type has all features of the existing types.
For example, consider an object that has both a name property and a email property: To combine types, you use the `&` operator as follows:
``` ```typescript
interface User { type typeAB = typeA & typeB;
name: string; ```
email: string;
}
const user: User = { The `typeAB` will have all properties from both typeA and typeB.
name: 'John Doe',
email: 'johndoe@example.com' Note that the union type uses the `|` operator that defines a variable which can hold a value of either `typeA` or `typeB`
};
```
Learn more from the following links: Learn more from the following links:
- [Intersection Types](https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#intersection-types) - [Intersection Types in TypeScript](https://www.typescripttutorial.net/typescript-tutorial/typescript-intersection-types/)
- [Implement Intersection Types in the Typescript](https://www.youtube.com/watch?v=adr7W5uyIMk)

@ -4,17 +4,16 @@ A Type Alias in TypeScript allows you to create a new name for a type.
Here's an example: Here's an example:
``` ```typescript
type Name = string; type Name = string;
type Age = number; type Age = number;
type User = { name: Name; age: Age }; type User = { name: Name; age: Age };
const user: User = { name: 'John', age: 30 }; 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`. 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: Learn more from the following links:
- [Type Aliases](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases) - [Type Aliases](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases)
- [TypeScript Tutorial - Type Aliases](youtube.com/watch?v=AmpwfbdFYL8)

@ -1,22 +1,20 @@
# Keyof Operator # keyof Operator
The keyof operator in TypeScript is used to get the union of keys from an object type. 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:
Here's an example of how it can be used:
``` ```typescript
interface User { interface User {
name: string; name: string;
age: number; age: number;
location: string; location: string;
} }
type UserKeys = keyof User; // "name" | "age" | "location" type UserKeys = keyof User; // "name" | "age" | "location"
const key: UserKeys = "name"; 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"`. 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: Learn more from the following links:
- [Keyof Type Operator](https://www.typescriptlang.org/docs/handbook/2/keyof-types.html#handbook-content) - [Keyof Type Operator](https://www.typescriptlang.org/docs/handbook/2/keyof-types.html#handbook-content)
- [Typescript Generics - Understanding the keyof Operator](https://www.youtube.com/watch?v=uy6fw4znJF4)

@ -2,30 +2,37 @@
In TypeScript, you can combine types using type union and type intersection. In TypeScript, you can combine types using type union and type intersection.
Type Union: ### 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: 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; type stringOrNumber = string | number;
let value: stringOrNumber = "hello"; let value: stringOrNumber = "hello";
value = 42;
``` value = 42;
```
### Type Intersection:
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: 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 { interface A {
a: string; a: string;
} }
interface B {
b: number; interface B {
} b: number;
type AB = A & B; }
let value: AB = { a: "hello", b: 42 };
``` type AB = A & B;
let value: AB = { a: "hello", b: 42 };
```
Learn more from the following links: Learn more from the following links:
- [Creating Types from Types](https://www.typescriptlang.org/docs/handbook/2/types-from-types.html#handbook-content) - [Union Types in TypeScript](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types)
- [Typescript - Combining Types with Generic](https://www.youtube.com/watch?v=Z3g8dVFsuMM) - [Intersection Types in TypeScript](https://www.typescripttutorial.net/typescript-tutorial/typescript-intersection-types/)
- [Type Aliases](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases)
- [Keyof Type Operator](https://www.typescriptlang.org/docs/handbook/2/keyof-types.html#handbook-content)

@ -1 +1,17 @@
# Typeof operator # typeof Operator
The `typeof` operator is used to check the type of a variable. It returns a string value representing the type of the variable.
```typescript
let value: string | number = "hello";
if (typeof value === "string") {
console.log("value is a string");
} else {
console.log("value is a number");
}
```
Learn more from the following links:
- [Type Guards and Differentiating Types](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#typeof-type-guards)

@ -1 +1,27 @@
# 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, interface, or type.
```typescript
class Bird {
fly() {
console.log('flying...');
}
layEggs() {
console.log('laying eggs...');
}
}
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:
- [instanceOf Operator](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#instanceof-narrowing)

@ -1 +1,22 @@
# Equality # Equality
TypeScript also uses switch statements and equality checks like `===`, `!==`, `==`, and `!=` to narrow types. For example:
```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);
}
}
```
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:
- [Equality Narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#equality-narrowing)

@ -1 +1,19 @@
# Truthiness # Truthiness
Truthiness might not be a word you’ll find in the dictionary, but it’s very much something you’ll hear about in JavaScript.
In JavaScript, we can use any expression in conditionals, `&&`s, `||`s, `if` statements, Boolean negations (`!`), and more. As an example, if statements don’t expect their condition to always have the type boolean.
```typescript
function getUsersOnlineMessage(numUsersOnline: number) {
if (numUsersOnline) {
return `There are ${numUsersOnline} online now!`;
}
return "Nobody's here. :(";
}
```
Learn more from the following links:
- [Truthiness Narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#truthiness-narrowing)

@ -1 +1,22 @@
# Type predicates # 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.
```typescript
function isString(value: unknown): value is string {
return typeof value === 'string';
}
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:
- [Type Guards and Differentiating Types](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)

@ -1 +1,7 @@
# Type guards # Type Guards
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.
Learn more from the following resources:
- [Type Guards - TypeScript Docs](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#typeof-type-guards)

@ -2,32 +2,32 @@
In TypeScript, functions can be typed in a few different ways to indicate the input parameters and return type of the function. In TypeScript, functions can be typed in a few different ways to indicate the input parameters and return type of the function.
1. Function declaration with types: Function declaration with types:
``` ```typescript
function add(a: number, b: number): number { function add(a: number, b: number): number {
return a + b; return a + b;
} }
``` ```
2. Arrow function with types: Arrow function with types:
``` ```typescript
const multiply = (a: number, b: number): number => { const multiply = (a: number, b: number): number => {
return a * b; return a * b;
}; };
``` ```
3. Function type: Function type:
``` ```typescript
let divide: (a: number, b: number) => number; let divide: (a: number, b: number) => number;
divide = (a, b) => {
return a / b; divide = (a, b) => {
}; return a / b;
``` };
```
Learn more from the following links: Learn more from the following links:
- [More on Functions](typescriptlang.org/docs/handbook/2/functions.html) - [TypeScript Functions](https://www.typescriptlang.org/docs/handbook/2/functions.html)
- [TypeScript Basics - Typing with functions](https://www.youtube.com/watch?v=do_8hnj45zg)

@ -2,22 +2,19 @@
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 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.
For example: ```typescript
function add(a: number, b: number): number;
function add(a: string, b: string): string;
``` function add(a: any, b: any): any {
function add(a: number, b: number): number; return a + b;
function add(a: string, b: string): string; }
function add(a: any, b: any): any { console.log(add(1, 2)); // 3
return a + b; console.log(add("Hello", " World")); // "Hello World"
} ```
console.log(add(1, 2)); // 3
console.log(add("Hello", " World")); // "Hello World"
```
Learn more from the following links: Learn more from the following links:
- [TypeScript - Function Overloading](https://www.tutorialsteacher.com/typescript/function-overloading)
- [Function Overloads](https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads) - [Function Overloads](https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads)

@ -2,37 +2,25 @@
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 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.
1. Function Declaration Syntax: > Function Declaration Syntax:
``` ```typescript
function name(param1: type1, param2: type2, ...): returnType { function name(param1: type1, param2: type2, ...): returnType {
// function body return value;
return value; }
} ```
```
> Function Expression Syntax:
2. Function Expression Syntax:
```typescript
``` function add(a: number, b: number): number {
let name: (param1: type1, param2: type2, ...) => returnType = return a + b;
function(param1: type1, param2: type2, ...): returnType { }
// function body
return value; let result = add(1, 2);
}; console.log(result); // 3
``` ```
For example:
```
function add(a: number, b: number): number {
return a + b;
}
let result = add(1, 2);
console.log(result); // 3
```
Learn more from the following links: Learn more from the following links:
- [Functions](https://www.typescriptlang.org/docs/handbook/functions.html) - [Functions in TypeScript](https://www.typescriptlang.org/docs/handbook/2/functions.html)
- [TypeScript Functions](https://www.w3schools.com/typescript/typescript_functions.php)
- [TypeScript - functions](youtube.com/watch?v=mblaKPWM9NU)

@ -4,33 +4,33 @@ In TypeScript, both types and interfaces can be used to define the structure of
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: 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 = { type Person = {
name: string; name: string;
age: number; age: number;
}; };
const person: Person = { const person: Person = {
name: "John Doe", name: "John Doe",
age: 30 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: 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 { interface Person {
name: string; name: string;
age: number; age: number;
} }
const person: Person = { const person: Person = {
name: "John Doe", name: "John Doe",
age: 30 age: 30
}; };
``` ```
Learn more from the following links: Learn more from the following links:
- [Interfaces vs. Type Aliases](https://www.typescriptlang.org/docs/handbook/advanced-types.html#interfaces-vs-type-aliases) - [Interfaces vs. Type Aliases](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces)
- [Interfaces vs Types in TypeScript](https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript) - [Interfaces vs Types in TypeScript](https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript)

@ -2,28 +2,25 @@
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. 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.
Here is an example: ```typescript
interface Shape {
width: number;
height: number;
}
``` interface Square extends Shape {
interface Shape { sideLength: number;
width: number; }
height: number;
}
interface Square extends Shape { let square: Square = {
sideLength: number; width: 10,
} height: 10,
sideLength: 10
};
```
let square: Square = { 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.
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: Learn more from the following links:
- [Interfaces](https://www.typescriptlang.org/docs/handbook/interfaces.html) - [Extending Interfaces](https://www.typescriptlang.org/docs/handbook/2/objects.html)
- [TypeScript - Extending Interfaces](https://www.typescriptlang.org/docs/handbook/interfaces.html#extending-interfaces)

@ -1,21 +1,21 @@
# Interface Declaration # 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` 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.
Here is an example of an interface declaration in TypeScript: Here is an example of an interface declaration in TypeScript:
``` ```typescript
interface Person { interface Person {
firstName: string; firstName: string;
lastName: string; lastName: string;
age?: number; age?: number;
getFullName(): string;
} 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. 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: Learn more from the following links:
- [Introduction - Declaration Files](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html) - [Extending Interfaces](https://www.typescriptlang.org/docs/handbook/2/objects.html)
- [Find and Install Declaration Files](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html#find-and-install-declaration-files)

@ -4,20 +4,22 @@ In TypeScript, a hybrid type is a type that combines multiple types into a singl
For example, you can create a hybrid type that can accept either a string or a number: For example, you can create a hybrid type that can accept either a string or a number:
``` ```typescript
type StringOrNumber = string | number; type StringOrNumber = string | number;
``` ```
Now, a value of type StringOrNumber can be either a string or a 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
let value: StringOrNumber = 'Hello, world!'; type Education = {
value = 42; degree: string;
``` school: string;
year: number;
You can also use hybrid types to create more complex types that can represent a combination of several different types of values. };
Learn more from the following links: type User = {
name: string;
- [TypeScript - Interface Hybrid Types](https://www.logicbig.com/tutorials/misc/typescript/interface-hybrid-types.html) age: number;
- [What is Hybrid types in typescript?](https://www.youtube.com/watch?v=eYAq1A4BsuI) email: string;
education: Education;
};

@ -4,21 +4,20 @@ Interfaces in TypeScript provide a way to define a contract for a type, which in
Here's an example of defining and using an interface in TypeScript: Here's an example of defining and using an interface in TypeScript:
``` ```typescript
interface User { interface User {
name: string; name: string;
age: number; age: number;
} }
const user: User = { const user: User = {
name: 'John Doe', name: 'John Doe',
age: 30 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. 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: Learn more from the following links:
- [TypeScript - Interfaces](https://www.typescriptlang.org/docs/handbook/interfaces.html) - [TypeScript - Interfaces](https://www.typescriptlang.org/docs/handbook/2/objects.html)
- [TypeScript Tutorial - Interfaces](https://www.youtube.com/watch?v=VbW6vWTaHOY)

@ -1,16 +1,15 @@
# Constructor Params # Constructor Params
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, 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:
``` ```typescript
class Example { class Example {
constructor(private name: string, public age: number) {} constructor(private name: string, public age: number) {}
} }
``` ```
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. 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: Learn more from the following links:
- [TypeScript - Construct](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors) - [TypeScript - Construct](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors)
- [TypeScript - Methods and constructors](https://www.youtube.com/watch?v=d9IJyMOmJoE)

@ -2,25 +2,25 @@
In TypeScript, you can achieve constructor overloading by using multiple constructors with different parameter lists in a single class. When you create an instance of the class, the constructor with the matching parameter list is called. Here's an example: In TypeScript, you can achieve constructor overloading by using multiple constructors with different parameter lists in a single class. When you create an instance of the class, the constructor with the matching parameter list is called. Here's an example:
``` ```typescript
class MyClass { class MyClass {
property1: number; property1: number;
property2: string; property2: string;
constructor(property1: number) { constructor(property1: number) {
this.property1 = property1; this.property1 = property1;
} }
constructor(property1: number, property2: string) { constructor(property1: number, property2: string) {
this.property1 = property1; this.property1 = property1;
this.property2 = property2; this.property2 = property2;
} }
} }
``` ```
In this example, we have two constructors with different parameter lists: constructor(property1: number) and constructor(property1: number, property2: string). When you create an instance of the class, the constructor with the matching parameter list is called: In this example, we have two constructors with different parameter lists: constructor(property1: number) and constructor(property1: number, property2: string). When you create an instance of the class, the constructor with the matching parameter list is called:
``` ```typescript
let myInstance1 = new MyClass(10); let myInstance1 = new MyClass(10);
let myInstance2 = new MyClass(10, "Hello"); let myInstance2 = new MyClass(10, "Hello");
``` ```
@ -28,4 +28,3 @@ let myInstance2 = new MyClass(10, "Hello");
Learn more from the following resources: Learn more from the following resources:
- [Constructors - TypeScript](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors) - [Constructors - TypeScript](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors)
- []()

@ -2,14 +2,12 @@
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: 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:
1. `Public:` This is the default access modifier. Properties and methods declared as public can be accessed from anywhere, both inside and outside the class. - `public:` This is the default access modifier. Properties and methods declared as public can be accessed from anywhere, both inside and outside the class.
2. `Private:` Properties and methods declared as private can only be accessed within the same class. They are not accessible from 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.
3. `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. - `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.
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. 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: Learn more from the following resources:
- [TypeScript Access Modifiers](https://www.typescripttutorial.net/typescript-tutorial/typescript-access-modifiers/) - [TypeScript Access Modifiers](https://www.typescripttutorial.net/typescript-tutorial/typescript-access-modifiers/)
- [TypeScript - Data Modifiers](https://www.tutorialsteacher.com/typescript/data-modifiers)

@ -2,11 +2,10 @@
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. 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.
For example: ```typescript
```
abstract class Animal { abstract class Animal {
abstract makeSound(): void; abstract makeSound(): void;
move(): void { move(): void {
console.log('moving...'); console.log('moving...');
} }
@ -21,5 +20,4 @@ class Dog extends Animal {
Learn more from the following resources: Learn more from the following resources:
- [Abstract Classes](https://www.typescriptlang.org/docs/handbook/classes.html#abstract-classes) - [Abstract Classes](https://www.typescriptlang.org/docs/handbook/2/classes.html#abstract-classes-and-members)
- [TypeScript - Abstract Class](https://www.tutorialsteacher.com/typescript/abstract-class)

@ -6,33 +6,33 @@ Inheritance refers to a mechanism where a subclass inherits properties and metho
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. 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.
For example: ```typescript
class Animal {
``` makeSound(): void {
class Animal { console.log('Making animal sound');
makeSound(): void { }
console.log('Making animal sound'); }
}
} class Dog extends Animal {
makeSound(): void {
class Dog extends Animal { console.log('Bark');
makeSound(): void { }
console.log('Bark'); }
}
} class Cat extends Animal {
makeSound(): void {
class Cat extends Animal { console.log('Meow');
makeSound(): void { }
console.log('Meow'); }
}
} let animal: Animal;
let animal: Animal; animal = new Dog();
animal = new Dog(); animal.makeSound(); // Output: Bark
animal.makeSound(); // Output: Bark
animal = new Cat(); animal = new Cat();
animal.makeSound(); // Output: Meow animal.makeSound(); // Output: Meow
``` ```
Learn more from the following resources: Learn more from the following resources:

@ -2,36 +2,29 @@
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. 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.
To override a method in TypeScript, you need to use the override keyword, and the signature of the method in the subclass must match exactly with the signature of the method in the parent class. To override a method in TypeScript, you need to use the `override` keyword, and the signature of the method in the subclass must match exactly with the signature of the method in the parent class.
For example: ```typescript
class Animal {
makeSound(): void {
console.log('Making animal sound');
}
}
``` class Dog extends Animal {
class Animal { makeSound(): void {
makeSound(): void { console.log('Bark');
console.log('Making animal sound'); }
} }
}
class Dog extends Animal { let animal: Animal;
makeSound(): void {
console.log('Bark');
}
}
let animal: Animal; animal = new Dog();
animal = new Dog(); animal.makeSound(); // Output: Bark
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. 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: Learn more from the following resources:
- [TypeScript - Overriding Methods](https://www.typescriptlang.org/docs/handbook/2/classes.html#overriding-methods) - [TypeScript - Overriding Methods](https://www.typescriptlang.org/docs/handbook/2/classes.html#overriding-methods)
- [Method Overriding in TypeScript](https://www.geeksforgeeks.org/method-overriding-in-typescript/)

@ -4,26 +4,24 @@ Classes in TypeScript are a blueprint for creating objects (instances of a class
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. 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.
For example: ```typescript
class Animal {
``` name: string;
class Animal { constructor(name: string) {
name: string; this.name = name;
constructor(name: string) { }
this.name = name;
} makeSound(): void {
makeSound(): void { console.log(`${this.name} is making a sound`);
console.log(`${this.name} is making a sound`); }
} }
}
const dog = new Animal('Dog');
const dog = new Animal('Dog'); dog.makeSound(); // Output: Dog is making a sound
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. 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: Learn more from the following resources:
- [Tutorial - Classes](https://www.typescriptlang.org/docs/handbook/2/classes.html) - [Tutorial - Classes](https://www.typescriptlang.org/docs/handbook/2/classes.html)
- [TypeScript Tutorial - Classes](https://www.youtube.com/watch?v=OsFwOzr3_sE)

@ -1,16 +1,16 @@
# Generic Types # Generic Types
Generic types in TypeScript allow you to write 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 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.
For example, the following is a generic function that takes a single argument of any data type and returns the same data type: For example, the following is a generic function that takes a single argument of any data type and returns the same data type:
``` ```typescript
function identity<T>(arg: T): T { function identity<T>(arg: T): T {
return arg; return arg;
} }
let output = identity<string>("Hello"); // type of output will be 'string' 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`. 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`.
@ -18,18 +18,17 @@ Generics can also be used with classes, interfaces, and object types, allowing t
For example: For example:
``` ```typescript
class GenericNumber<T> { class GenericNumber<T> {
zeroValue: T; zeroValue: T;
add: (x: T, y: T) => T; add: (x: T, y: T) => T;
} }
let myGenericNumber = new GenericNumber<number>(); let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0; myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; }; myGenericNumber.add = function(x, y) { return x + y; };
``` ```
Learn more from the following resources: Learn more from the following resources:
- [Generics - TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html#generics) - [Hello World of Generics](https://www.typescriptlang.org/docs/handbook/2/generics.html#hello-world-of-generics)
- [Typescript Generics Tutorial](https://www.youtube.com/watch?v=nViEqpgwxHE)

@ -2,27 +2,26 @@
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 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.
Constraints are specified using the extends keyword, followed by the type that the type parameter must extend or implement. Constraints are specified using the `extends` keyword, followed by the type that the type parameter must extend or implement.
For example: ```typescript
interface Lengthwise {
length: number;
}
``` function loggingIdentity<T extends Lengthwise>(arg: T): T {
interface Lengthwise { // Now we know it has a .length property, so no more error
length: number; console.log(arg.length);
}
function loggingIdentity<T extends Lengthwise>(arg: T): T { return arg;
console.log(arg.length); // Now we know it has a .length property, so no more error }
return arg;
}
loggingIdentity(3); // Error, number doesn't have a .length property loggingIdentity(3); // Error, number doesn't have a .length property
loggingIdentity({length: 10, value: 3}); // OK 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. 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: Learn more from the following resources:
- [Generic Constraints - TypeScript](https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints) - [Generic Constraints - TypeScript](https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints)
- [TypeScript Course - Generics Constraints](https://www.youtube.com/watch?v=hLP2evgcAq4)

@ -4,17 +4,16 @@ Generics in TypeScript are a way to write code that can work with multiple data
For example, the following is a generic function that takes a single argument of any data type and returns the same data type: For example, the following is a generic function that takes a single argument of any data type and returns the same data type:
``` ```typescript
function identity<T>(arg: T): T { function identity<T>(arg: T): T {
return arg; return arg;
} }
let output = identity<string>("Hello"); // type of output will be 'string' 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"`. 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: Learn more from the following resources:
- [Hello World of Generics](https://www.typescriptlang.org/docs/handbook/2/generics.html#hello-world-of-generics) - [Hello World of Generics](https://www.typescriptlang.org/docs/handbook/2/generics.html#hello-world-of-generics)
- [Typescript Generics Tutorial](https://www.youtube.com/watch?v=nViEqpgwxHE)

@ -4,28 +4,30 @@ Decorators are a feature of TypeScript that allow you to modify the behavior of
Here's an example of how you might use a decorator in TypeScript: Here's an example of how you might use a decorator in TypeScript:
``` ```typescript
function log(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) { function log(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value; const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling ${propertyKey} with arguments: ${args}`); descriptor.value = function (...args: any[]) {
return originalMethod.apply(this, args); console.log(`Calling ${propertyKey} with arguments: ${args}`);
}; return originalMethod.apply(this, args);
return descriptor; };
}
return descriptor;
class Calculator { }
@log
add(a: number, b: number): number { class Calculator {
return a + b; @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 const calculator = new Calculator();
// Output: 3 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. 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.

@ -4,26 +4,27 @@ The Partial type in TypeScript allows you to make all properties of a type optio
Here's an example of using the Partial type in TypeScript: Here's an example of using the Partial type in TypeScript:
``` ```typescript
interface User { interface User {
name: string; name: string;
age: number; age: number;
email: string; email: string;
} }
function createUser(user: Partial<User>): User { function createUser(user: Partial<User>): User {
return { return {
name: 'John Doe', name: 'John Doe',
age: 30, age: 30,
email: 'john.doe@example.com', email: 'john.doe@example.com',
...user ...user
}; };
} }
const newUser = createUser({ name: 'Jane Doe' }); const newUser = createUser({ name: 'Jane Doe' });
console.log(newUser);
// Output: { name: 'Jane Doe', age: 30, email: 'john.doe@example.com' } console.log(newUser);
``` // Output: { name: 'Jane Doe', age: 30, email: 'john.doe@example.com' }
```
Learn more from the following links: Learn more from the following links:

@ -2,24 +2,20 @@
Pick constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type. Pick constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type.
``` ```typescript
interface Todo { interface Todo {
title: string; title: string;
description: string; description: string;
completed: boolean; completed: boolean;
} }
type TodoPreview = Pick<Todo, "title" | "completed">; type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = { const todo: TodoPreview = {
title: "Clean room", title: "Clean room",
completed: false, completed: false,
}; };
```
todo;
const todo: TodoPreview
```
Learn more from the following links: Learn more from the following links:

@ -2,38 +2,29 @@
Omit constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals). Omit constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals).
```typescript
``` interface Todo {
interface Todo { title: string;
title: string; description: string;
description: string; completed: boolean;
completed: boolean; createdAt: number;
createdAt: number; }
}
type TodoPreview = Omit<Todo, "description">;
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
const todo: TodoPreview = { title: "Clean room",
title: "Clean room", completed: false,
completed: false, createdAt: 1615544252770,
createdAt: 1615544252770, };
};
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
todo;
const todoInfo: TodoInfo = {
const todo: TodoPreview title: "Pick up kids",
description: "Kindergarten closes at 5pm",
type TodoInfo = Omit<Todo, "completed" | "createdAt">; };
```
const todoInfo: TodoInfo = {
title: "Pick up kids",
description: "Kindergarten closes at 5pm",
};
todoInfo;
const todoInfo: TodoInfo
```
Learn more from the following links: Learn more from the following links:

@ -2,18 +2,18 @@
Readonly constructs a type with all properties of Type set to readonly, meaning the properties of the constructed type cannot be reassigned. 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 { interface Todo {
title: string; title: string;
} }
const todo: Readonly<Todo> = { const todo: Readonly<Todo> = {
title: "Delete inactive users", title: "Delete inactive users",
}; };
todo.title = "Hello"; // Cannot assign to 'title' because it is a read-only property.
Cannot assign to 'title' because it is a read-only property. todo.title = "Hello";
``` ```
Learn more from the following links: Learn more from the following links:

@ -2,24 +2,20 @@
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. 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.
``` ```typescript
interface CatInfo { interface CatInfo {
age: number; age: number;
breed: string; breed: string;
} }
type CatName = "miffy" | "boris" | "mordred"; type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName, CatInfo> = { const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" }, miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" }, boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" }, mordred: { age: 16, breed: "British Shorthair" },
}; };
```
cats.boris;
const cats: Record<CatName, CatInfo>
```
Learn more from the following links: Learn more from the following links:

@ -2,17 +2,11 @@
Exclude constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers. Exclude constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers.
``` ```typescript
type T0 = Exclude<"a" | "b" | "c", "a">; type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // "c"
type T0 = "b" | "c" type T2 = Exclude<string | number | (() => void), Function>; // string | number
type T1 = Exclude<"a" | "b" | "c", "a" | "b">; ```
type T1 = "c"
type T2 = Exclude<string | number | (() => void), Function>;
type T2 = string | number
```
Learn more from the following links: Learn more from the following links:

@ -2,14 +2,10 @@
Extract constructs a type by extracting from Type all union members that are assignable to Union. Extract constructs a type by extracting from Type all union members that are assignable to Union.
``` ```typescript
type T0 = Extract<"a" | "b" | "c", "a" | "f">; type T0 = Extract<"a" | "b" | "c", "a" | "f">;
// ^ = type T0 = "a"
type T0 = "a" ```
type T1 = Extract<string | number | (() => void), Function>;
type T1 = () => void
```
Learn more from the following links: Learn more from the following links:

@ -1,15 +1,14 @@
# Non Nullable # Non Nullable
Nun Nullable constructs a type by excluding null and undefined from Type. Non-Nullable constructs a type by excluding `null` and `undefined` from Type.
``` ```typescript
type T0 = NonNullable<string | number | undefined>; type T0 = NonNullable<string | number | undefined>;
// type T0 = string | number
type T0 = string | number type T1 = NonNullable<string[] | null | undefined>;
type T1 = NonNullable<string[] | null | undefined>; // type T1 = string[]
```
type T1 = string[]
```
Learn more from the following links: Learn more from the following links:

@ -2,36 +2,35 @@
Parameters constructs a tuple type from the types used in the parameters of a function type Type. Parameters constructs a tuple type from the types used in the parameters of a function type Type.
``` ```typescript
declare function f1(arg: { a: number; b: string }): void; type T0 = Parameters<() => string>;
type T0 = Parameters<() => string>; // type T0 = []
type T0 = []
type T1 = Parameters<(s: string) => void>; type T1 = Parameters<(s: string) => void>;
type T1 = [s: string] // type T1 = [s: string]
type T2 = Parameters<<T>(arg: T) => T>;
type T2 = [arg: unknown] type T2 = Parameters<<T>(arg: T) => T>;
type T3 = Parameters<typeof f1>; // type T2 = [arg: unknown]
type T3 = [arg: { declare function f1(arg: { a: number, b: string }): void;
a: number; type T3 = Parameters<typeof f1>;
b: string; // type T3 = [arg: {
}] // a: number;
type T4 = Parameters<any>; // b: string;
// }]
type T4 = unknown[]
type T5 = Parameters<never>; type T4 = Parameters<any>;
// type T4 = unknown[]
type T5 = never
type T6 = Parameters<string>; type T5 = Parameters<never>;
Type 'string' does not satisfy the constraint '(...args: any) => any'. // type T5 = never
type T6 = never type T6 = Parameters<string>;
type T7 = Parameters<Function>; // ^ Type 'string' does not satisfy the constraint '(...args: any) => any'.
Type 'Function' does not satisfy the constraint '(...args: any) => any'.
Type 'Function' provides no match for the signature '(...args: any): any'. type T7 = Parameters<Function>;
// ^ Type 'Function' does not satisfy the constraint '(...args: any) => any'.
type T7 = never ```
```
Learn more from the following links: Learn more from the following links:

@ -1,43 +1,39 @@
# Return type # ReturnType
Return type constructs a type consisting of the return type of function Type. Return type constructs a type consisting of the return type of function Type.
``` ```typescript
declare function f1(): { a: number; b: string }; type T0 = ReturnType<() => string>;
type T0 = ReturnType<() => string>; // type T0 = string
type T0 = string type T1 = ReturnType<(s: string) => void>;
type T1 = ReturnType<(s: string) => void>; // type T1 = void
type T1 = void type T2 = ReturnType<<T>() => T>;
type T2 = ReturnType<<T>() => T>; // type T2 = unknown
type T2 = unknown type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
type T3 = ReturnType<<T extends U, U extends number[]>() => T>; // type T3 = number[]
type T3 = number[] declare function f1(): { a: number; b: string };
type T4 = ReturnType<typeof f1>; type T4 = ReturnType<typeof f1>;
// type T4 = {
// a: number;
// b: string;
// }
type T4 = { type T5 = ReturnType<any>;
a: number; // type T5 = any
b: string;
}
type T5 = ReturnType<any>;
type T5 = any type T6 = ReturnType<never>;
type T6 = ReturnType<never>; // type T6 = never
type T6 = never type T7 = ReturnType<string>;
type T7 = ReturnType<string>; // ^ Type 'string' does not satisfy the constraint '(...args: any) => any'.
Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T7 = any type T8 = ReturnType<Function>;
type T8 = ReturnType<Function>; // ^ Type 'Function' does not satisfy the constraint '(...args: any) => any'.
Type 'Function' does not satisfy the constraint '(...args: any) => any'. ```
Type 'Function' provides no match for the signature '(...args: any): any'.
type T8 = any
```
Learn more from the following links: Learn more from the following links:

@ -1,33 +1,28 @@
# Instance type # InstanceType
This type constructs a type consisting of the instance type of a constructor function in Type. This type constructs a type consisting of the instance type of a constructor function in Type.
``` ```typescript
class C { class C {
x = 0; x = 0;
y = 0; y = 0;
} }
type T0 = InstanceType<typeof C>;
type T0 = C type T0 = InstanceType<typeof C>;
type T1 = InstanceType<any>; // type T0 = C
type T1 = any type T1 = InstanceType<any>;
type T2 = InstanceType<never>; // type T1 = any
type T2 = never type T2 = InstanceType<never>;
type T3 = InstanceType<string>; // type T2 = never
Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
type T3 = any type T3 = InstanceType<string>;
type T4 = InstanceType<Function>; // ^ Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.
Type 'Function' provides no match for the signature 'new (...args: any): any'.
type T4 = any type T4 = InstanceType<Function>;
``` // ^ Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.
```
Learn more from the following links: Learn more from the following links:

@ -1,20 +1,17 @@
# Awaited # 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. 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.
``` ```typescript
type A = Awaited<Promise<string>>; type A = Awaited<Promise<string>>;
// type A = string
type A = string type B = Awaited<Promise<Promise<number>>>;
// type B = number
type B = Awaited<Promise<Promise<number>>>; type C = Awaited<boolean | Promise<number>>;
// type C = number | boolean
type B = number ```
type C = Awaited<boolean | Promise<number>>;
type C = number | boolean
```
Learn more from the following links: Learn more from the following links:

@ -2,11 +2,12 @@
TypeScript provides several utility types that can be used to manipulate and transform existing types. Here are some of the most common ones: TypeScript provides several utility types that can be used to manipulate and transform existing types. Here are some of the most common ones:
1. Partial: makes all properties of a type optional. - `Partial`: makes all properties of a type optional.
2. Readonly: makes all properties of a type read-only. - `Readonly`: makes all properties of a type read-only.
3. Pick: allows you to pick specific properties from a type. - `Pick`: allows you to pick specific properties from a type.
4. Omit: allows you to omit specific properties from a type. - `Omit`: allows you to omit specific properties from a type.
5. Exclude: creates a type that is the set difference of A and B. - `Exclude`: creates a type that is the set difference of A and B.
- ..and more.
Learn more from the following links: Learn more from the following links:

@ -4,7 +4,7 @@ Mapped types in TypeScript are a way to create a new type based on an existing t
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`: 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`:
``` ```typescript
type Readonly<T> = { type Readonly<T> = {
readonly [P in keyof T]: T[P]; readonly [P in keyof T]: T[P];
}; };
@ -18,4 +18,3 @@ In this example, the `Readonly` mapped type takes an object type `T` and creates
Learn more from the following links: Learn more from the following links:
- [Mapped Types](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#handbook-content) - [Mapped Types](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#handbook-content)
- [Mapped Types - Advanced TypeScript](https://www.youtube.com/watch?v=RjQpep8fBdo)

@ -4,7 +4,7 @@ Conditional types in TypeScript are a way to select a type based on a condition.
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: 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 Extends<T, U> = T extends U ? T : U;
type A = Extends<string, any>; // type A is 'string' type A = Extends<string, any>; // type A is 'string'

@ -4,7 +4,7 @@ Literal types in TypeScript are a way to specify a value exactly, rather than ju
For example, the following is a literal type that represents a value of 42: For example, the following is a literal type that represents a value of 42:
``` ```typescript
type Age = 42; type Age = 42;
let age: Age = 42; // ok let age: Age = 42; // ok
@ -16,4 +16,3 @@ In this example, the `Age` literal type is created by using the number `42` as a
Learn more from the following links: Learn more from the following links:
- [Literal Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) - [Literal Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types)
- [TypeScript Literal Types Explained](https://www.youtube.com/watch?v=JXVrPRmnQt0)

@ -4,16 +4,15 @@ Template literal types in TypeScript are a way to manipulate string values as ty
For example, the following is a template literal type that concatenates two strings: For example, the following is a template literal type that concatenates two strings:
``` ```typescript
type Name = `Mr. ` + string; type Name = `Mr. ` + string;
let name: Name = `Mr. Smith`; // ok let name: Name = `Mr. Smith`; // ok
let name: Name = `Mrs. Smith`; // error 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. "`. 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: Learn more from the following links:
- [Template Literal Types](https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html#handbook-content) - [Template Literal Types](https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html#handbook-content)
- [TypeScript Template Literal Types](https://www.youtube.com/watch?v=nskIP1iyrAo)

@ -4,10 +4,10 @@ Recursive types in TypeScript are a way to define a type that references itself.
For example, the following is a recursive type that represents a linked list: For example, the following is a recursive type that represents a linked list:
``` ```typescript
type LinkedList<T> = T & { next: LinkedList<T> }; type LinkedList<T> = T & { next: LinkedList<T> };
let list: LinkedList<number> = { value: 1, next: { value: 2, next: { value: 3, next: 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. 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.

@ -4,18 +4,18 @@ In TypeScript, namespaces are used to organize and share code across multiple fi
Here's an example of how you can use namespaces in TypeScript: Here's an example of how you can use namespaces in TypeScript:
``` ```typescript
// myNamespace.ts // myNamespace.ts
namespace MyNamespace { namespace MyNamespace {
export function doSomething() { export function doSomething() {
console.log("Doing something..."); console.log("Doing something...");
}
} }
}
// main.ts // main.ts
/// <reference path="myNamespace.ts" /> /// <reference path="myNamespace.ts" />
MyNamespace.doSomething(); // Output: "Doing something..." 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". 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".

@ -4,20 +4,19 @@ Ambient modules in TypeScript are used to declare external modules or third-part
Here's an example of how you can use ambient modules in TypeScript: Here's an example of how you can use ambient modules in TypeScript:
``` ```typescript
// myModule.d.ts // myModule.d.ts
declare module "my-module" { declare module "my-module" {
export function doSomething(): void; export function doSomething(): void;
} }
// main.ts // main.ts
import * as myModule from "my-module"; import * as myModule from "my-module";
myModule.doSomething(); 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. 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: Learn more from the following links:
- [Ambient Modules](https://www.typescriptlang.org/docs/handbook/modules.html#ambient-modules) - [Ambient Modules](https://www.typescriptlang.org/docs/handbook/modules.html#ambient-modules)
- [TypeScript Ambient Module](https://www.w3schools.blog/ambient-module-typescript)

@ -4,16 +4,16 @@ In TypeScript, external modules allow you to organize and share code across mult
Here's an example of how you can use external modules in TypeScript: Here's an example of how you can use external modules in TypeScript:
``` ```typescript
// myModule.ts // myModule.ts
export function doSomething() { export function doSomething() {
console.log("Doing something..."); console.log("Doing something...");
} }
// main.ts // main.ts
import { doSomething } from "./myModule"; import { doSomething } from "./myModule";
doSomething(); // Output: "Doing something..." 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. 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.

@ -4,27 +4,27 @@ In TypeScript, namespace augmentation is a way to extend or modify existing name
Here's an example of how you can use namespace augmentation in TypeScript: Here's an example of how you can use namespace augmentation in TypeScript:
``` ```typescript
// myModule.d.ts // myModule.d.ts
declare namespace MyModule { declare namespace MyModule {
export interface MyModule { export interface MyModule {
newFunction(): void; 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!");
} }
}
}
// main.ts const obj = new MyModule.MyModule();
/// <reference path="myModule.d.ts" /> obj.newFunction(); // Output: "I am a new function in MyModule!"
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. 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.

@ -4,21 +4,21 @@ In TypeScript, global augmentation is a way to add declarations to the global sc
Here's an example of how you can use global augmentation in TypeScript: Here's an example of how you can use global augmentation in TypeScript:
``` ```typescript
// myModule.d.ts // myModule.d.ts
declare namespace NodeJS { declare namespace NodeJS {
interface Global { interface Global {
myGlobalFunction(): void; myGlobalFunction(): void;
} }
} }
// main.ts // main.ts
global.myGlobalFunction = function () { global.myGlobalFunction = function () {
console.log("I am a global function!"); console.log("I am a global function!");
}; };
myGlobalFunction(); // Output: "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". 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".

@ -11,18 +11,18 @@ External modules are used to organize code across multiple files. They are defin
Here is an example of how you can use internal modules in TypeScript: Here is an example of how you can use internal modules in TypeScript:
``` ```typescript
// myModule.ts // myModule.ts
namespace MyModule { namespace MyModule {
export function doSomething() { export function doSomething() {
console.log("Doing something..."); console.log("Doing something...");
}
} }
}
// main.ts // main.ts
/// <reference path="myModule.ts" /> /// <reference path="myModule.ts" />
MyModule.doSomething(); // Output: "Doing something..." MyModule.doSomething(); // Output: "Doing something..."
``` ```
Learn more from the following links: Learn more from the following links:

@ -1,20 +1,8 @@
# Formatting # Formatting
Formatting in TypeScript refers to the way code is indented, spaced, and arranged to make it easier to read and understand. Consistent formatting helps to ensure that code is readable, maintainable, and consistent across multiple developers and projects. 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.
Here's an example of basic formatting in TypeScript: Visit the following resources to learn more:
``` - [Prettier Website](https://prettier.io)
function add(a: number, b: number): number { - [Why Prettier](https://prettier.io/docs/en/why-prettier.html)
return a + b;
}
const result = add(3, 5);
console.log(result); // Output: 8
```
In this example, the code is indented with two spaces, and each line of code is separated by a line break. The opening brace `{` is placed on the same line as the function declaration, and the closing brace } is indented on a new line. This is a common style for formatting code in TypeScript.
Learn more from the following links:
- [How to format strings in TypeScript?](https://www.tutorialspoint.com/how-to-format-strings-in-typescript)

@ -1,32 +1,9 @@
# Linting # Linting
With ESLint you can impose the coding standard using a certain set of standalone rules.
Linting in TypeScript refers to the process of using a linter to analyze your code and find potential problems or issues. Linters can help you enforce a consistent coding style, catch syntax errors, and identify problematic patterns in your code. Visit the following resources to learn more:
Here's an example of how you can use TSLint, a popular TypeScript linter, in your TypeScript project: - [ESLint Official Website](https://eslint.org/)
- [Introduction to ESLint](https://dev.to/shivambmgupta/eslint-what-why-when-how-5f1d)
``` - [ESLint Quickstart - find errors automatically](https://www.youtube.com/watch?v=qhuFviJn-es)
// Step 1: Install TSLint
npm install tslint
// Step 2: Create a TSLint configuration file (tslint.json)
{
"extends": [
"tslint:recommended"
],
"rules": {
"semicolon": [true, "always"],
"quotemark": [true, "double"]
}
}
// Step 3: Run TSLint on your TypeScript code
./node_modules/.bin/tslint myFile.ts
```
In this example, we first install TSLint using the npm package manager. Next, we create a TSLint configuration file, "tslint.json", that extends the recommended TSLint rules and sets specific rules for semicolons and quotes.
Learn more from the following links:
- [Linting TypeScript](https://www.youtube.com/watch?v=020KjoCox70)
- [Linting in TypeScript using ESLint and Prettier](https://blog.logrocket.com/linting-typescript-eslint-prettier/)

@ -1,49 +1,11 @@
# Useful Packages # Useful Packages
There are many useful packages available for TypeScript that can help you improve your development workflow and add new functionality to your projects. Here are a few popular packages to consider using in your TypeScript projects: 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.
1. Lodash: A utility library that provides a wide range of helpful functions for working with arrays, objects, and other data structures. - [zod](https://zod.dev/): A TypeScript-first data validation library
- [ts-morph](https://github.com/dsherret/ts-morph): A TypeScript-first API for manipulating TypeScript code
``` - [ts-node](https://typestrong.org/ts-node/): A TypeScript execution and REPL for node.js
// Step 1: Install Lodash - [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.
npm install lodash - [typesync](https://github.com/jeffijoe/typesync): Install missing TypeScript typings for dependencies in your package.json.
- [tsd](https://github.com/SamVerschueren/tsd) - TypeScript Definition Manager
// Step 2: Import Lodash in your TypeScript code - [type-fest](https://github.com/sindresorhus/type-fest) - A collection of essential TypeScript types
import * as _ from "lodash";
// Step 3: Use Lodash in your code
const result = _.map([1, 2, 3], (num) => num * 3);
console.log(result); // Output: [3, 6, 9]
```
2. Axios: A popular HTTP client for making REST API requests.
```
// Step 1: Install Axios
npm install axios
// Step 2: Import Axios in your TypeScript code
import axios from "axios";
// Step 3: Use Axios in your code
axios.get("https://jsonplaceholder.typicode.com/posts")
.then((response) => {
console.log(response.data);
});
```
3. Moment.js: A library for working with dates and times.
```
// Step 1: Install Moment.js
npm install moment
// Step 2: Import Moment.js in your TypeScript code
import * as moment from "moment";
// Step 3: Use Moment.js in your code
const date = moment().format("MMMM Do YYYY, h:mm:ss a");
console.log(date); // Output: "February 1st 2023, 2:00:00 pm"
```
These are just a few examples of the many useful packages available for TypeScript. By using these and other packages, you can improve your development workflow and add new functionality to your projects.

@ -1,13 +1,16 @@
# Build Tools # Build Tools
Build tools are used to compile and bundle your TypeScript code into a format that can be run in a browser or other environment. Some popular build tools for TypeScript include: 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.
- Webpack: A popular module bundler that can compile and bundle TypeScript code, as well as other assets such as CSS, images, and more. 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!
- Babel: A popular JavaScript compiler that can be used to compile TypeScript code into a format that is compatible with older browsers and environments.
- Rollup: A module bundler that can be used to compile and bundle TypeScript code for small to medium-sized projects.
- Parcel: A fast and efficient zero-configuration bundler that can compile and bundle TypeScript code.
Learn more from the following links: Visit the following resources to learn more:
- [Integrating with Build Tools](https://www.typescriptlang.org/docs/handbook/integrating-with-build-tools.html#handbook-content) - [webpack is a static module bundler for modern JavaScript applications](https://webpack.js.org/)
- [TypeScript Build Tools](https://www.javatpoint.com/typescript-build-tools) - [Vite Next Generation Frontend Tooling](https://vitejs.dev)
- [Parcel is a zero configuration build tool for the web](https://parceljs.org/)
- [esbuild is an extremely fast JavaScript bundler and minifier](https://esbuild.github.io/)
- [swc is a super-fast compiler written in Rust](https://swc.rs/)
- [tsup is a zero-config TypeScript build tool](https://tsup.egoist.sh/)
- [Rollup is a module bundler for JavaScript](https://rollupjs.org/guide/en/)
- [tsdx is a zero-config CLI for TypeScript package development](https://tsdx.io/)

@ -1,24 +1,3 @@
# Ecosystem # Ecosystem
The TypeScript ecosystem refers to the set of tools, libraries, and packages that are available to support the development of applications using TypeScript. Here are a few examples of the components that make up the TypeScript ecosystem: Have a look at the linked nodes for different tools and frameworks that you can use to build your projects.
1. TypeScript Compiler
```
// Example: Compiling TypeScript code using the TypeScript compiler
tsc index.ts
```
2. TypeScript Definition Files
```
// Example: Installing TypeScript definition files for the Lodash library
npm install @types/lodash
```
3. TypeScript Plugins for Editor Environments
4. TypeScript-based Frameworks and Libraries
Learn more from the following links:
- [tsc, the TypeScript compiler](https://www.typescriptlang.org/docs/handbook/2/basic-types.html#tsc-the-typescript-compiler)
Loading…
Cancel
Save