Compare commits

...

16 Commits

Author SHA1 Message Date
syedmouaazfarrukh
f780487c71 Adding content to 101-typescript-types 2023-02-01 09:25:46 -08:00
syedmouaazfarrukh
a0ba51be1b Adding content to 104-undefined 2023-02-01 09:24:58 -08:00
syedmouaazfarrukh
7c206ed3f4 Adding content to 115-type-assertions 2023-02-01 08:35:46 -08:00
syedmouaazfarrukh
a530062bfc Adding content to 111-utility-types 2023-02-01 08:23:42 -08:00
syedmouaazfarrukh
85fcad3c1e 102-type-inference, 103-type-compatibility, 110-decorators 2023-02-01 08:01:49 -08:00
syedmouaazfarrukh
32c2199411 114-ecosystem 2023-02-01 07:48:32 -08:00
syedmouaazfarrukh
aabe43008a 113-modules 2023-02-01 07:34:26 -08:00
syedmouaazfarrukh
bf39bc3478 112-advanced-types 2023-02-01 07:05:23 -08:00
syedmouaazfarrukh
36e8abd38c Adding content to 109-generics 2023-02-01 05:05:23 -08:00
syedmouaazfarrukh
0d2be7724f Adding content to 108-classes 2023-02-01 04:53:50 -08:00
syedmouaazfarrukh
e38408f415 Adding content to 107-interfaces 2023-02-01 01:48:30 -08:00
syedmouaazfarrukh
411387bda6 Adding content to 106-functions 2023-02-01 01:28:00 -08:00
syedmouaazfarrukh
94ebd6cc89 Adding content to 104-combining-types 2023-01-31 09:19:06 -08:00
syedmouaazfarrukh
71af9e3070 Adding content to 100-typescript 2023-01-31 08:24:13 -08:00
syedmouaazfarrukh
d59455425b Adding content to 103-running-typescript 2023-01-31 08:13:18 -08:00
syedmouaazfarrukh
f5295476f8 Adding content to 102-install-configure 2023-01-31 07:54:30 -08:00
88 changed files with 2043 additions and 88 deletions

View File

@@ -1 +1,16 @@
# Typescript vs javascript
# TypeScript vs JavaScript
TypeScript is a superset of JavaScript that adds optional type annotations and other features such as interfaces, classes, and namespaces. JavaScript is a dynamically-typed language that is primarily used for client-side web development and can also be used for server-side development.
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.
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.
3. 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.
Learn more from the following links:
- [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)

View File

@@ -1 +1,7 @@
# 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.
You can use JavaScript libraries in TypeScript projects by either including the JavaScript files directly or using type definitions for the library. Type definitions provide type information for JavaScript libraries, making it easier to use them in TypeScript.
On the other hand, you can use TypeScript code in JavaScript projects by simply compiling the TypeScript code into JavaScript. The generated JavaScript code can be used in any JavaScript environment, and it will work the same way as regular JavaScript code.

View File

@@ -1 +1,30 @@
# 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:
- **target**: the version of JavaScript to compile to.
- **module**: the module system to use.
- **stric**": enables/disables strict type checking.
- **outDir**: the directory to output the compiled JavaScript files.
- **rootDir**: the root directory of the TypeScript files.
- **exclude**: an array of file/directory patterns to exclude from the compilation.
Example:
```
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src",
"exclude": ["node_modules"]
}
}
```
Learn more from the following links:
- [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)

View File

@@ -1 +1,30 @@
# 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:
1. target
2. module
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:
- [Compiler Options](https://www.typescriptlang.org/docs/handbook/compiler-options.html#compiler-options)
- [TypeScript Compiler Options](https://www.youtube.com/watch?v=I1ZFsPK0Q-Y&vl=en)

View File

@@ -1 +1,56 @@
# Install configure
# Install Configure
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:
```
npm init
```
- Install TypeScript as a project dependency by running the following command:
```
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:
```
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src",
"exclude": ["node_modules"]
}
}
```
- Compile your TypeScript code using the following command:
```
tsc
```
Note: You can also compile individual TypeScript files by specifying the file name after the tsc command.For example:
```
tsc index.ts
```
And you're all set! You can now start writing TypeScript code in your project.
Learn more from the following links:
- [How To Configure TypeScript](https://www.youtube.com/watch?v=SEnAS_ooHeA)
- [Installing TypeScript](https://www.typescriptlang.org/download)

View File

@@ -1 +1,23 @@
# 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.
You can use the `tsc` command to compile your TypeScript code by running the following command in your terminal or command prompt:
```
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:
```
tsc index.ts
```
The `tsc` command has several options and flags that you can use to customize the compilation process. For example, you can use the `--target` option to specify the version of JavaScript to compile to, or the `--outDir` option to specify the output directory for the compiled JavaScript files.
You can run `tsc --help` to see a list of all the available options and flags.
Learn more from the following links:
- [tsc CLI Options](https://www.typescriptlang.org/docs/handbook/compiler-options.html#using-the-cli)

View File

@@ -1 +1,8 @@
# 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.
Learn more from the following links:
- [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)

View File

@@ -1 +1,7 @@
# 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.
Learn more from the following links:
- [TypeScript - Playground](https://www.typescriptlang.org/play)

View File

@@ -1 +1,17 @@
# Running typescript
# Running TypeScript
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)
2. Compile the TypeScript code into JavaScript using the TypeScript compiler:
```
tsc app.ts
```
3. Run the generated JavaScript code using a JavaScript runtime environment such as Node.js:
```
node app.js
```
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)

View File

@@ -1 +1,16 @@
# Typescript
# TypeScript
TypeScript is a statically-typed programming language that is a superset of JavaScript. It was developed and is maintained by Microsoft. TypeScript was created to address the challenges of building large-scale JavaScript applications and adds optional type annotations, classes, interfaces, and other features to the language.
The main benefits of using TypeScript include:
- Type Safety
- Improved Tooling
- Improved Maintainability
- Backwards Compatibility
Learn more from the folowing links:
- [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)
- [Learn Complete TypeScript](https://www.youtube.com/watch?v=30LWjhZzg50)

View File

@@ -1 +1,14 @@
# Boolean
# Boolean
`boolean` is a primitive data type in TypeScript that represents a truth value, either true or false.
For example:
```
let isTrue: boolean = true;
let isFalse: boolean = false;
```
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)

View File

@@ -1 +1,16 @@
# Number
# Number
It is a primitive data type in TypeScript that represents numeric values. It includes both integer and floating-point values.
For example:
```
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:
- [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)

View File

@@ -1 +1,13 @@
# String
# String
In TypeScript, the string is sequence of char values and also considered as an object.
Syntax:
```
var var_name = new String(string);
```
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)

View File

@@ -1 +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.
Example:
```
function sayHi(): void {
console.log('Hi!')
}
let speech: void = sayHi();
console.log(speech); //Output: undefined
```
Learn more from the following links:
- [void](https://www.typescriptlang.org/docs/handbook/2/functions.html#void)

View File

@@ -1 +1,20 @@
# 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.
For example:
```
let x: undefined;
x = undefined; // valid
x = null; // not valid
function doSomething(): undefined {
// ...
return undefined;
}
```
Learn more from the following links:
- [null and undefined](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined)

View File

@@ -1 +1,13 @@
# Null
# Null
In TypeScript, both undefined and null actually have their types named undefined and null respectively. Much like void, theyre not extremely useful on their own:
```
// Not much else we can assign to these variables!
let u: undefined = undefined;
let n: null = null;
```
Learn more from the following links:
- [Null and Undefined](https://www.typescriptlang.org/docs/handbook/basic-types.html#null-and-undefined)

View File

@@ -1 +1,17 @@
# Interface
# Interface
TypeScript allows you to specifically type an object using an interface that can be reused by multiple objects.
Example:
```
interface Publication {
isbn: string;
author: string;
publisher: string;
}
```
Learn more from the following links:
- [Reusable Types (Interfaces)](https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html#reusable-types-interfaces)

View File

@@ -1 +1,25 @@
# Class
# Class
In TypeScript, a class is a blueprint for creating objects with specific properties and methods. Classes are a fundamental concept in object-oriented programming. Here is an example of a simple class in TypeScript:
```
class Car {
make: string;
model: string;
year: number;
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
drive() {
console.log(`Driving my ${this.year} ${this.make} ${this.model}`);
}
}
```
Learn more from the following links:
- [Classes](https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html#classes)

View File

@@ -1 +1,18 @@
# Enum
# Enum
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:
```
enum Direction {
Up = 1,
Down,
Left,
Right,
}
```
Learn more from the following links:
- [TypeScript - Enums](https://www.typescriptlang.org/docs/handbook/enums.html)

View File

@@ -1 +1,7 @@
# 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. Well learn more about the syntax T<U> when we cover generics.
Learn more from the following links:
- [Arrays](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#arrays)

View File

@@ -1 +1,11 @@
# Tuple
# Tuple
A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions.
```
type StringNumberPair = [string, number];
```
Learn more from the following links:
- [Tuple Types](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types)

View File

@@ -1 +1,19 @@
# 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 thats syntactically legal:
```
let obj: any = { x: 0 };
// None of the following lines of code will throw compiler errors.
// Using `any` disables all further type checking, and it is assumed
// you know the environment better than TypeScript.
obj.foo();
obj();
obj.bar = 100;
obj = "hello";
const n: number = obj;
```
Learn more from the following links:
- [any](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any)

View File

@@ -1 +1,19 @@
# Object
# Object
To define an object type, we simply list its properties and their types.
For example, heres a function that takes a point-like object:
```
// The parameter's type annotation is an object type
function printCoord(pt: { x: number; y: number }) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3, y: 7 });
```
Learn more from the following links:
- [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](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#object-types)

View File

@@ -1 +1,19 @@
# Unknown
# Unknown
The unknown type represents any value. This is similar to the any type, but is safer because its not legal to do anything with an unknown value:
```
function f1(a: any) {
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.
Learn more from the following links:
- [Unknown](https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown)

View File

@@ -1 +1,28 @@
# 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 is a subtype of, and assignable to, every type; however, no type is a subtype of, or assignable to, never (except never itself). Even any isnt assignable to never.
Examples of functions returning never:
```
// Function returning never must not have a reachable end point
function error(message: string): never {
throw new Error(message);
}
// Inferred return type is never
function fail() {
return error("Something failed");
}
// Function returning never must not have a reachable end point
function infiniteLoop(): never {
while (true) {}
}
```
Learn more from the following links:
- [Never](https://www.typescriptlang.org/docs/handbook/basic-types.html#never)

View File

@@ -1 +1,17 @@
# As const
# As Const
`as const` is a type assertion in TypeScript that allows you to assert that an expression has a specific type, and that its value should be treated as a read-only value.
For example:
```
const colors = ['red', 'green', 'blue'] as const;
// colors is now of type readonly ['red', 'green', 'blue']
```
Using as const allows TypeScript to infer more accurate types for constants, which can lead to improved type checking and better type inference in your code.
Learn more from the following links:
- [const assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions)

View File

@@ -1 +1,14 @@
# As type
# As Type
as is a type assertion in TypeScript that allows you to tell the compiler to treat a value as a specific type, regardless of its inferred type.
For example:
```
let num = 42;
let str = num as string;
// str is now of type string, even though num is a number
```
It's important to note that type assertions do not change the runtime type of a value, and do not cause any type of conversion. They simply provide a way for the programmer to override the type inference performed by the compiler.

View File

@@ -1 +1,13 @@
# As any
# As Any
`any` is a special type in TypeScript that represents a value of any type. When a value is declared with the any type, the compiler will not perform any type checks or type inference on that value.
For example:
```
let anyValue: any = 42;
// we can assign any value to anyValue, regardless of its type
anyValue = 'Hello, world!';
anyValue = true;
```

View File

@@ -1 +1,18 @@
# Non null assertion
# Non Null Assertion
The non-null assertion operator (!) is a type assertion in TypeScript that allows you to tell the compiler that a value will never be null or undefined.
For example:
```
let name: string | null = null;
// we use the non-null assertion operator to tell the compiler that name will never be null
let nameLength = name!.length;
```
The non-null assertion operator is used to assert that a value is not null or undefined, and to tell the compiler to treat the value as non-nullable. However, it's important to be careful when using the non-null assertion operator, as it can lead to runtime errors if the value is actually `null` or `undefined`.
Learn more from the following links:
- [Non-null assertion operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator)

View File

@@ -1 +1,26 @@
# Type assertions
# Type Assertions
Type assertions in TypeScript are a way to tell the compiler to treat a value as a specific type, regardless of its inferred type.
There are two syntaxes for type assertions in TypeScript:
1. The "angle-bracket" syntax: `<T>value`
2. The "as" syntax: value as `T`
For example:
```
let num = 42;
// using angle-bracket syntax
let str = <string>num;
// using as syntax
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.
Learn more from the following links:
- [Type Assertions](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions)

View File

@@ -1 +1,23 @@
# 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.
For example:
```
// Each property can be a string or an RGB tuple.
const palette = {
red: [255, 0, 0],
green: "#00ff00",
bleu: [0, 0, 255]
// ^^^^ sacrebleu - we've made a typo!
};
// We want to be able to use array methods on 'red'...
const redComponent = palette.red.at(0);
// or string methods on 'green'...
const greenNormalized = palette.green.toUpperCase();
```
Learn more from the following links:
- [Satisfies Keyword](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator)

View File

@@ -1 +1,26 @@
# Typescript types
# Typescript Types
TypeScript has several built-in types, including:
1. number
2. string
3. boolean
4. any
5. void
6. null and undefined
7. never
8. object
9. symbol
10. Enumerated types (enum)
11. Tuple types
12. Array types
13. Union types
14. Intersection types
15. Type aliases
16. Type assertions
You can also create custom types in TypeScript using interfaces, classes, and type aliases.
Learn more from the following links:
- [Transcript - Everyday Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html)

View File

@@ -1 +1,16 @@
# Type inference
# Type Inference
Type inference in TypeScript refers to the process of automatically determining the type of a variable based on the value assigned to it. This allows you to write code that is more concise and easier to understand, as the TypeScript compiler can deduce the types of variables without you having to explicitly specify them.
Here's an example of type inference in TypeScript:
```
let name = "John Doe";
```
In this example, the TypeScript compiler automatically infers that the type of the name variable is string. This means that you can use the name variable just like any other string in your code, and the TypeScript compiler will ensure that you don't perform any invalid operations on it.
Learn more from the following links:
- [Type Inference](https://www.typescriptlang.org/docs/handbook/type-inference.html#handbook-content)
- [Type Inference in TypeScript](https://www.tutorialsteacher.com/typescript/type-inference)

View File

@@ -1 +1,24 @@
# 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.
Here's an example of type compatibility in TypeScript:
```
interface Point {
x: number;
y: number;
}
let p1: Point = { x: 10, y: 20 };
let p2: { x: number; y: number } = p1;
console.log(p2.x); // Output: 10
```
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:
- [Type Compatibility](https://www.typescriptlang.org/docs/handbook/type-compatibility.html)
- [Tutorial - Type Compatibility in TypeScript](youtube.com/watch?v=wqm5ibtCSf0)

View File

@@ -1 +1,16 @@
# 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.
For example, consider a function that takes either a string or a number as an argument:
```
function combine(input1: string | number, input2: string | number) {
return input1 + input2;
}
```
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/unions-and-intersections.html)

View File

@@ -1 +1,22 @@
# 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.
For example, consider an object that has both a name property and a email property:
```
interface User {
name: string;
email: string;
}
const user: User = {
name: 'John Doe',
email: 'johndoe@example.com'
};
```
Learn more from the following links:
- [Intersection Types](https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#intersection-types)
- [Implement Intersection Types in the Typescript](https://www.youtube.com/watch?v=adr7W5uyIMk)

View File

@@ -1 +1,20 @@
# Type aliases
# Type Aliases
A Type Alias in TypeScript allows you to create a new name for a type.
Here's an example:
```
type Name = string;
type Age = number;
type User = { name: Name; age: Age };
const user: User = { name: 'John', age: 30 };
```
In the example above, `Name` and `Age` are type aliases for `string` and `number` respectively. And `User` is a type alias for an object with properties `name` of type `Name` and `age` of type `Age`.
Learn more from the following links:
- [Type Aliases](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases)
- [TypeScript Tutorial - Type Aliases](youtube.com/watch?v=AmpwfbdFYL8)

View File

@@ -1 +1,22 @@
# Keyof operator
# Keyof Operator
The keyof operator in TypeScript is used to get the union of keys from an object type.
Here's an example of how it can be used:
```
interface User {
name: string;
age: number;
location: string;
}
type UserKeys = keyof User; // "name" | "age" | "location"
const key: UserKeys = "name";
```
In this example, `UserKeys` is a type that represents the union of keys from the `User` interface, which is `"name"` | `"age"` | `"location"`. And a constant named `key` with the type `UserKeys` is declared with the value `"name"`.
Learn more from the following links:
- [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)

View File

@@ -1 +1,31 @@
# Combining types
# Combining Types
In TypeScript, you can combine types using type union and type intersection.
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:
```
type stringOrNumber = string | number;
let value: stringOrNumber = "hello";
value = 42;
```
Type Intersection:
The intersection operator `&` is used to intersect two or more types into a single type that represents the properties of all the types. For example:
```
interface A {
a: string;
}
interface B {
b: number;
}
type AB = A & B;
let value: AB = { a: "hello", b: 42 };
```
Learn more from the following links:
- [Creating Types from Types](https://www.typescriptlang.org/docs/handbook/2/types-from-types.html#handbook-content)
- [Typescript - Combining Types with Generic](https://www.youtube.com/watch?v=Z3g8dVFsuMM)

View File

@@ -1 +1,33 @@
# Typing functions
# Typing Functions
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 add(a: number, b: number): number {
return a + b;
}
```
2. Arrow function with types:
```
const multiply = (a: number, b: number): number => {
return a * b;
};
```
3. Function type:
```
let divide: (a: number, b: number) => number;
divide = (a, b) => {
return a / b;
};
```
Learn more from the following links:
- [More on Functions](typescriptlang.org/docs/handbook/2/functions.html)
- [TypeScript Basics - Typing with functions](https://www.youtube.com/watch?v=do_8hnj45zg)

View File

@@ -1 +1,23 @@
# Function overloading
# Function Overloading
Function Overloading in TypeScript allows multiple functions with the same name but with different parameters to be defined. The correct function to call is determined based on the number, type, and order of the arguments passed to the function at runtime.
For example:
```
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
return a + b;
}
console.log(add(1, 2)); // 3
console.log(add("Hello", " World")); // "Hello World"
```
Learn more from the following links:
- [TypeScript - Function Overloading](https://www.tutorialsteacher.com/typescript/function-overloading)
- [Function Overloads](https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads)

View File

@@ -1 +1,38 @@
# Functions
# Functions
Functions are a core building block in TypeScript. Functions allow you to wrap a piece of code and reuse it multiple times. Functions in TypeScript can be either declared using function declaration syntax or function expression syntax.
1. Function Declaration Syntax:
```
function name(param1: type1, param2: type2, ...): returnType {
// function body
return value;
}
```
2. Function Expression Syntax:
```
let name: (param1: type1, param2: type2, ...) => returnType =
function(param1: type1, param2: type2, ...): returnType {
// function body
return value;
};
```
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:
- [Functions](https://www.typescriptlang.org/docs/handbook/functions.html)
- [TypeScript Functions](https://www.w3schools.com/typescript/typescript_functions.php)
- [TypeScript - functions](youtube.com/watch?v=mblaKPWM9NU)

View File

@@ -1 +1,36 @@
# Types vs interfaces
# Types vs Interfaces
In TypeScript, both types and interfaces can be used to define the structure of objects and enforce type checks. However, there are some differences between the two.
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:
```
type Person = {
name: string;
age: number;
};
const person: Person = {
name: "John Doe",
age: 30
};
```
Interfaces, on the other hand, are used to describe the structure of objects and classes. They can be created using the interface keyword. For example:
```
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "John Doe",
age: 30
};
```
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 Types in TypeScript](https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript)

View File

@@ -1 +1,29 @@
# Extending interfaces
# Extending Interfaces
In TypeScript, you can extend an interface by creating a new interface that inherits from the original interface using the "extends" keyword. The new interface can include additional properties, methods, or redefine the members of the original interface.
Here is an example:
```
interface Shape {
width: number;
height: number;
}
interface Square extends Shape {
sideLength: number;
}
let square: Square = {
width: 10,
height: 10,
sideLength: 10
};
```
In this example, the Square interface extends the Shape interface and adds an additional property sideLength. A variable of type Square must have all the properties defined in both Shape and Square interfaces.
Learn more from the following links:
- [Interfaces](https://www.typescriptlang.org/docs/handbook/interfaces.html)
- [TypeScript - Extending Interfaces](https://www.typescriptlang.org/docs/handbook/interfaces.html#extending-interfaces)

View File

@@ -1 +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.
Here is an example of an interface declaration in TypeScript:
```
interface Person {
firstName: string;
lastName: string;
age?: number;
getFullName(): string;
}
```
In this example, the Person interface defines four properties: `firstName`, `lastName`, `age`, and a method `getFullName()`. The age property is optional, indicated by the `?` symbol. Any class or object that implements the `Person` interface must have these properties and method.
Learn more from the following links:
- [Introduction - Declaration Files](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)
- [Find and Install Declaration Files](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html#find-and-install-declaration-files)

View File

@@ -1 +1,23 @@
# Hybrid types
# Hybrid Types
In TypeScript, a hybrid type is a type that combines multiple types into a single type. The resulting type is considered a union of those types. This allows you to specify that a value can have multiple types, rather than just one.
For example, you can create a hybrid type that can accept either a string or a number:
```
type StringOrNumber = string | number;
```
Now, a value of type StringOrNumber can be either a string or a number:
```
let value: StringOrNumber = 'Hello, world!';
value = 42;
```
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:
- [TypeScript - Interface Hybrid Types](https://www.logicbig.com/tutorials/misc/typescript/interface-hybrid-types.html)
- [What is Hybrid types in typescript?](https://www.youtube.com/watch?v=eYAq1A4BsuI)

View File

@@ -1 +1,24 @@
# Interfaces
# Interfaces
Interfaces in TypeScript provide a way to define a contract for a type, which includes a set of properties, methods, and events. It's used to enforce a structure for an object, class, or function argument. Interfaces are not transpiled to JavaScript and are only used by TypeScript at compile-time for type-checking purposes.
Here's an example of defining and using an interface in TypeScript:
```
interface User {
name: string;
age: number;
}
const user: User = {
name: 'John Doe',
age: 30
};
```
In this example, the User interface defines the structure of the user object with two properties, name and age. The object is then typed as User using a type-assertion : User.
Learn more from the following links:
- [TypeScript - Interfaces](https://www.typescriptlang.org/docs/handbook/interfaces.html)
- [TypeScript Tutorial - Interfaces](https://www.youtube.com/watch?v=VbW6vWTaHOY)

View File

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

View File

@@ -1 +1,31 @@
# Constructor overloading
# Constructor Overloading
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:
```
class MyClass {
property1: number;
property2: string;
constructor(property1: number) {
this.property1 = property1;
}
constructor(property1: number, property2: string) {
this.property1 = property1;
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:
```
let myInstance1 = new MyClass(10);
let myInstance2 = new MyClass(10, "Hello");
```
Learn more from the following resources:
- [Constructors - TypeScript](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors)
- []()

View File

@@ -1 +1,15 @@
# Access modifiers
# Access Modifiers
In TypeScript, access modifiers are keywords used to control the visibility and accessibility of class properties and methods. There are three access modifiers in TypeScript:
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.
2. `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.
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:
- [TypeScript Access Modifiers](https://www.typescripttutorial.net/typescript-tutorial/typescript-access-modifiers/)
- [TypeScript - Data Modifiers](https://www.tutorialsteacher.com/typescript/data-modifiers)

View File

@@ -1 +1,25 @@
# Abstract classes
# Abstract Classes
Abstract classes in TypeScript are classes that cannot be instantiated on their own and must be subclassed by other classes. Abstract classes provide a blueprint for other classes and can have abstract methods, which are methods without a body and must be overridden by the subclass. These classes are useful for defining a common interface or basic functionality that other classes can inherit and build upon.
For example:
```
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log('moving...');
}
}
class Dog extends Animal {
makeSound(): void {
console.log('bark');
}
}
```
Learn more from the following resources:
- [Abstract Classes](https://www.typescriptlang.org/docs/handbook/classes.html#abstract-classes)
- [TypeScript - Abstract Class](https://www.tutorialsteacher.com/typescript/abstract-class)

View File

@@ -1 +1,39 @@
# Inheritance vs polymorphism
# Inheritance vs Polymorphism
Inheritance and polymorphism are two fundamental concepts in object-oriented programming, and they are supported in TypeScript as well.
Inheritance refers to a mechanism where a subclass inherits properties and methods from its parent class. This allows a subclass to reuse the code and behavior of its parent class while also adding or modifying its own behavior. In TypeScript, inheritance is achieved using the extends keyword.
Polymorphism refers to the ability of an object to take on many forms. This allows objects of different classes to be treated as objects of a common class, as long as they share a common interface or inheritance hierarchy. In TypeScript, polymorphism is achieved through method overriding and method overloading.
For example:
```
class Animal {
makeSound(): void {
console.log('Making animal sound');
}
}
class Dog extends Animal {
makeSound(): void {
console.log('Bark');
}
}
class Cat extends Animal {
makeSound(): void {
console.log('Meow');
}
}
let animal: Animal;
animal = new Dog();
animal.makeSound(); // Output: Bark
animal = new Cat();
animal.makeSound(); // Output: Meow
```
Learn more from the following resources:
- [Inheritance and Polymorphism In TypeScript](https://www.youtube.com/watch?v=Sn6K57YSuwU)

View File

@@ -1 +1,37 @@
# Method overriding
# Method Overriding
In TypeScript, method overriding is a mechanism where a subclass provides a new implementation for a method that is already defined in its parent class. This allows the subclass to inherit the behavior of the parent class, but change its behavior to fit its own needs.
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:
```
class Animal {
makeSound(): void {
console.log('Making animal sound');
}
}
class Dog extends Animal {
makeSound(): void {
console.log('Bark');
}
}
let animal: Animal;
animal = new Dog();
animal.makeSound(); // Output: Bark
```
In this example, the `Dog` class overrides the makeSound method defined in the Animal class and provides its own implementation. When the `makeSound` method is called on an instance of the `Dog` class, it will use the implementation in the `Dog` class rather than the implementation in the `Animal` class.
Learn more from the following resources:
- [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/)

View File

@@ -1 +1,29 @@
# Classes
# Classes
Classes in TypeScript are a blueprint for creating objects (instances of a class), providing a way to structure objects and encapsulate data and behavior. Classes in TypeScript have a similar syntax to classes in other object-oriented programming languages, such as Java and C#.
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:
```
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): void {
console.log(`${this.name} is making a sound`);
}
}
const dog = new Animal('Dog');
dog.makeSound(); // Output: Dog is making a sound
```
In this example, the `Animal` class has a name field, a constructor that sets the value of the `name` field, and a `makeSound` method. An instance of the `Animal` class can be created using the `new` keyword, and its methods and properties can be accessed using dot notation.
Learn more from the following resources:
- [Tutorial - Classes](https://www.typescriptlang.org/docs/handbook/2/classes.html)
- [TypeScript Tutorial - Classes](https://www.youtube.com/watch?v=OsFwOzr3_sE)

View File

@@ -1 +1,35 @@
# 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.
For example, the following is a generic function that takes a single argument of any data type and returns the same data type:
```
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("Hello"); // type of output will be 'string'
```
In this example, the `identity` function takes a single argument of any data type and returns the same data type. The actual data type is specified when the function is called by using `<string>` before the argument `Hello`.
Generics can also be used with classes, interfaces, and object types, allowing them to work with multiple data types as well.
For example:
```
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };
```
Learn more from the following resources:
- [Generics - TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html#generics)
- [Typescript Generics Tutorial](https://www.youtube.com/watch?v=nViEqpgwxHE)

View File

@@ -1 +1,28 @@
# Generic constraints
# Generic Constraints
Generic constraints in TypeScript allow you to specify the requirements for the type parameters used in a generic type. These constraints ensure that the type parameter used in a generic type meets certain requirements.
Constraints are specified using the extends keyword, followed by the type that the type parameter must extend or implement.
For example:
```
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
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({length: 10, value: 3}); // OK
```
In this example, the `Lengthwise` interface defines a `length` property. The `loggingIdentity` function uses a generic type parameter `T` that is constrained by the `Lengthwise` interface, meaning that the type parameter must extend or implement the `Lengthwise` interface. This constraint ensures that the length property is available on the argument passed to the `loggingIdentity` function.
Learn more from the following resources:
- [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)

View File

@@ -1 +1,20 @@
# Generics
# Generics
Generics in TypeScript are a way to write code that can work with multiple data types, instead of being limited to a single data type. Generics allow you to write functions, classes, and interfaces that take one or more type parameters, which act as placeholders for the actual data types that will be used when the function, class, or interface is used.
For example, the following is a generic function that takes a single argument of any data type and returns the same data type:
```
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("Hello"); // type of output will be 'string'
```
In this example, the `identity` function takes a single argument of any data type and returns the same data type. The actual data type is specified when the function is called by using `<string>` before the argument `"Hello"`.
Learn more from the following resources:
- [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)

View File

@@ -1 +1,34 @@
# Decorators
# Decorators
Decorators are a feature of TypeScript that allow you to modify the behavior of a class, property, method, or parameter. They are a way to add additional functionality to existing code, and they can be used for a wide range of tasks, including logging, performance optimization, and validation.
Here's an example of how you might use a decorator in TypeScript:
```
function log(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling ${propertyKey} with arguments: ${args}`);
return originalMethod.apply(this, args);
};
return descriptor;
}
class Calculator {
@log
add(a: number, b: number): number {
return a + b;
}
}
const calculator = new Calculator();
calculator.add(1, 2);
// Output: Calling add with arguments: 1,2
// Output: 3
```
In this example, we use the `@log` decorator to modify the behavior of the `add` method in the `Calculator` class. The `log` decorator logs the arguments passed to the method before calling the original method. This allows us to see what arguments are being passed to the method, without having to modify the method's code.
Learn more from the following links:
- [Decorators](https://www.typescriptlang.org/docs/handbook/decorators.html#handbook-content)

View File

@@ -1 +1,30 @@
# Partial
# Partial
The Partial type in TypeScript allows you to make all properties of a type optional. This is useful when you need to create an object with only a subset of the properties of an existing type.
Here's an example of using the Partial type in TypeScript:
```
interface User {
name: string;
age: number;
email: string;
}
function createUser(user: Partial<User>): User {
return {
name: 'John Doe',
age: 30,
email: 'john.doe@example.com',
...user
};
}
const newUser = createUser({ name: 'Jane Doe' });
console.log(newUser);
// Output: { name: 'Jane Doe', age: 30, email: 'john.doe@example.com' }
```
Learn more from the following links:
- [Partial<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)

View File

@@ -1 +1,26 @@
# Pick
# Pick
Pick constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type.
```
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
todo;
const todo: TodoPreview
```
Learn more from the following links:
- [Pick<Type, Keys>](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys)

View File

@@ -1 +1,40 @@
# Omit
# Omit
Omit constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals).
```
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};
todo;
const todo: TodoPreview
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:
- [Omit<Type, Keys>](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)

View File

@@ -1 +1,20 @@
# Readonly
# Readonly
Readonly constructs a type with all properties of Type set to readonly, meaning the properties of the constructed type cannot be reassigned.
```
interface Todo {
title: string;
}
const todo: Readonly<Todo> = {
title: "Delete inactive users",
};
todo.title = "Hello";
Cannot assign to 'title' because it is a read-only property.
```
Learn more from the following links:
- [Readonly<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype)

View File

@@ -1 +1,26 @@
# Record
# Record
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.
```
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
cats.boris;
const cats: Record<CatName, CatInfo>
```
Learn more from the following links:
- [Record<Keys, Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)

View File

@@ -1 +1,19 @@
# Exclude
# Exclude
Exclude constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers.
```
type T0 = Exclude<"a" | "b" | "c", "a">;
type T0 = "b" | "c"
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:
- [Exclude<UnionType, ExcludedMembers>](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers)

View File

@@ -1 +1,16 @@
# Extract
# Extract
Extract constructs a type by extracting from Type all union members that are assignable to Union.
```
type T0 = Extract<"a" | "b" | "c", "a" | "f">;
type T0 = "a"
type T1 = Extract<string | number | (() => void), Function>;
type T1 = () => void
```
Learn more from the following links:
- [Extract<Type, Union>](https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union)

View File

@@ -1 +1,16 @@
# Non nullable
# Non Nullable
Nun Nullable constructs a type by excluding null and undefined from Type.
```
type T0 = NonNullable<string | number | undefined>;
type T0 = string | number
type T1 = NonNullable<string[] | null | undefined>;
type T1 = string[]
```
Learn more from the following links:
- [NonNullable<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype)

View File

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

View File

@@ -1 +1,44 @@
# Return type
# Return type
Return type constructs a type consisting of the return type of function Type.
```
declare function f1(): { a: number; b: string };
type T0 = ReturnType<() => string>;
type T0 = string
type T1 = ReturnType<(s: string) => void>;
type T1 = void
type T2 = ReturnType<<T>() => T>;
type T2 = unknown
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
type T3 = number[]
type T4 = ReturnType<typeof f1>;
type T4 = {
a: number;
b: string;
}
type T5 = ReturnType<any>;
type T5 = any
type T6 = ReturnType<never>;
type T6 = never
type T7 = ReturnType<string>;
Type 'string' does not satisfy the constraint '(...args: any) => any'.
type T7 = any
type T8 = ReturnType<Function>;
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:
- [ReturnType<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype)

View File

@@ -1 +1,34 @@
# Instance type
# Instance type
This type constructs a type consisting of the instance type of a constructor function in Type.
```
class C {
x = 0;
y = 0;
}
type T0 = InstanceType<typeof C>;
type T0 = C
type T1 = InstanceType<any>;
type T1 = any
type T2 = InstanceType<never>;
type T2 = never
type T3 = InstanceType<string>;
Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
type T3 = any
type T4 = InstanceType<Function>;
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
```
Learn more from the following links:
- [InstanceType<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#instancetypetype)

View File

@@ -1 +1,21 @@
# 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.
```
type A = Awaited<Promise<string>>;
type A = string
type B = Awaited<Promise<Promise<number>>>;
type B = number
type C = Awaited<boolean | Promise<number>>;
type C = number | boolean
```
Learn more from the following links:
- [Awaited<Type>](https://www.typescriptlang.org/docs/handbook/utility-types.html#awaitedtype)

View File

@@ -1 +1,13 @@
# Utility types
# Utility Types
TypeScript provides several utility types that can be used to manipulate and transform existing types. Here are some of the most common ones:
1. Partial: makes all properties of a type optional.
2. Readonly: makes all properties of a type read-only.
3. Pick: allows you to pick specific properties from a type.
4. Omit: allows you to omit specific properties from a type.
5. Exclude: creates a type that is the set difference of A and B.
Learn more from the following links:
- [TypeScript - Utility Types](https://www.typescriptlang.org/docs/handbook/utility-types.html)

View File

@@ -1 +1,21 @@
# Mapped types
# Mapped Types
Mapped types in TypeScript are a way to create a new type based on an existing type, where each property of the existing type is transformed in some way. Mapped types are declared using a combination of the `keyof` operator and a type that maps each property of the existing type to a new property type.
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`:
```
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
let obj = { x: 10, y: 20 };
let readonlyObj: Readonly<typeof obj> = obj;
```
In this example, the `Readonly` mapped type takes an object type `T` and creates a new type with all properties of `T` but with their type changed to `readonly`. The keyof `T` operator is used to extract the names of the properties of `T`, and the `T[P]` syntax is used to access the type of each property of `T`. The `readonly` keyword is used to make the properties of the new type `readonly`.
Learn more from the following links:
- [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)

View File

@@ -1 +1,19 @@
# Conditional types
# Conditional Types
Conditional types in TypeScript are a way to select a type based on a condition. They allow you to write a type that dynamically chooses a type based on the types of its inputs. Conditional types are declared using a combination of the `infer` keyword and a type that tests a condition and selects a type based on the result of the test.
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:
```
type Extends<T, U> = T extends U ? T : U;
type A = Extends<string, any>; // type A is 'string'
type B = Extends<any, string>; // type B is 'string'
```
In this example, the Extends conditional type takes two types T and U and returns the type of the first argument `T` if it extends the second argument `U`, and the type of the second argument `U` otherwise. The T extends `U` syntax is used to test whether `T extends U`, and the `? T : U` syntax is used to select the type `T` if the test passes and the type `U` otherwise.
Learn more from the following links:
- [Conditional Types](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#handbook-content)
- [Conditional Types - Advanced TypeScript](https://www.youtube.com/watch?v=QFWrbNehKk0)

View File

@@ -1 +1,19 @@
# Literal types
# Literal Types
Literal types in TypeScript are a way to specify a value exactly, rather than just a type. Literal types can be used to enforce that a value must be of a specific type and a specific value. Literal types are created by using a literal value, such as a string, number, or boolean, as a type.
For example, the following is a literal type that represents a value of 42:
```
type Age = 42;
let age: Age = 42; // ok
let age: Age = 43; // error
```
In this example, the `Age` literal type is created by using the number `42` as a type. This type can then be used to enforce that a value must be of type `number` and have the value `42`.
Learn more from the following links:
- [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)

View File

@@ -1 +1,19 @@
# Template literal types
# Template Literal Types
Template literal types in TypeScript are a way to manipulate string values as types. They allow you to create a type based on the result of string manipulation or concatenation. Template literal types are created using the backtick (``) character and string manipulation expressions within the type.
For example, the following is a template literal type that concatenates two strings:
```
type Name = `Mr. ` + string;
let name: Name = `Mr. Smith`; // ok
let name: Name = `Mrs. Smith`; // error
```
In this example, the `Name` template literal type is created by concatenating the string `"Mr. "` with the type `string`. This type can then be used to enforce that a value must be a string that starts with `"Mr. "`.
Learn more from the following links:
- [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)

View File

@@ -1 +1,13 @@
# Recursive types
# Recursive Types
Recursive types in TypeScript are a way to define a type that references itself. Recursive types are used to define complex data structures, such as trees or linked lists, where a value can contain one or more values of the same type.
For example, the following is a recursive type that represents a linked list:
```
type LinkedList<T> = T & { next: LinkedList<T> };
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.

View File

@@ -1 +1,18 @@
# Advanced types
# Advanced Types
Advanced types in TypeScript are a set of advanced type constructs that allow for more complex and expressive type systems. Some of the most commonly used advanced types in TypeScript include:
- Intersection Types
- Union Types
- Type Aliases
- Conditional Types
- Index Types
- Mapped Types
- Type Guards
These advanced types allow for more complex and expressive type systems, and enable you to write code that is safer, more maintainable, and easier to understand. By leveraging these advanced types, you can write code that is more robust, less prone to errors, and easier to maintain.
Learn more from the following links:
- [Advanced Topics](https://www.typescriptlang.org/docs/handbook/type-compatibility.html#advanced-topics)
- [Tutorial of Typescript - Advanced Types](https://www.youtube.com/playlist?list=PLw5h0DiJ-9PBIgIyd2ZA1CVnJf0BLFJg2)

View File

@@ -1 +1,26 @@
# Namespaces
# Namespaces
In TypeScript, namespaces are used to organize and share code across multiple files. Namespaces allow you to group related functionality into a single unit and prevent naming conflicts.
Here's an example of how you can use namespaces in TypeScript:
```
// myNamespace.ts
namespace MyNamespace {
export function doSomething() {
console.log("Doing something...");
}
}
// main.ts
/// <reference path="myNamespace.ts" />
MyNamespace.doSomething(); // Output: "Doing something..."
```
In this example, we use the `namespace` keyword in the "myNamespace.ts" file to define a namespace "MyNamespace". Within the namespace, we export a function "doSomething".
Learn more from the following resources:
- [Overview of Namespaces](https://www.typescriptlang.org/docs/handbook/namespaces.html)
- [Namespaces and Modules](https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html)
- [TypeScript - Using Namespaces](typescriptlang.org/docs/handbook/namespaces-and-modules.html#using-namespaces)

View File

@@ -1 +1,23 @@
# Ambient modules
# Ambient Modules
Ambient modules in TypeScript are used to declare external modules or third-party libraries in a TypeScript program. Ambient modules provide type information for modules that have no TypeScript declarations, but are available in the global scope.
Here's an example of how you can use ambient modules in TypeScript:
```
// myModule.d.ts
declare module "my-module" {
export function doSomething(): void;
}
// main.ts
import * as myModule from "my-module";
myModule.doSomething();
```
In this example, we declare an ambient module "my-module" in the `myModule.d.ts` file. This declaration provides type information for the "my-module" module, including the "doSomething" function that is exported from the module.
Learn more from the following links:
- [Ambient Modules](https://www.typescriptlang.org/docs/handbook/modules.html#ambient-modules)
- [TypeScript Ambient Module](https://www.w3schools.blog/ambient-module-typescript)

View File

@@ -1 +1,23 @@
# External modules
# External Modules
In TypeScript, external modules allow you to organize and share code across multiple files. External modules in TypeScript follow the CommonJS or ES modules standards.
Here's an example of how you can use external modules in TypeScript:
```
// myModule.ts
export function doSomething() {
console.log("Doing something...");
}
// main.ts
import { doSomething } from "./myModule";
doSomething(); // Output: "Doing something..."
```
In this example, we use the "export" keyword in the "myModule.ts" file to export the "doSomething" function, making it available for other files to use.
Learn more from the following links:
- [External Module](https://www.javatpoint.com/typescript-module)
- [TypeScript - External Module](https://learncodeweb.com/typescript/modules-in-typescript-explain-with-an-example/)

View File

@@ -1 +1,33 @@
# Namespace augmentation
# Namespace Augmentation
In TypeScript, namespace augmentation is a way to extend or modify existing namespaces. This is useful when you want to add new functionality to existing namespaces or to fix missing or incorrect declarations in third-party libraries.
Here's an example of how you can use namespace augmentation in TypeScript:
```
// myModule.d.ts
declare namespace MyModule {
export interface MyModule {
newFunction(): void;
}
}
// main.ts
/// <reference path="myModule.d.ts" />
namespace MyModule {
export class MyModule {
public newFunction() {
console.log("I am a new function in MyModule!");
}
}
}
const obj = new MyModule.MyModule();
obj.newFunction(); // Output: "I am a new function in MyModule!"
```
In this example, we use namespace augmentation to add a new function "newFunction" to the "MyModule" namespace. This is done in the declaration file `myModule.d.ts` by declaring a new interface "MyModule" within the "MyModule" namespace and adding the "newFunction" function to it.
Learn more from the following links:
- [Module Augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)

View File

@@ -1 +1,27 @@
# Global augmentation
# Global Augmentation
In TypeScript, global augmentation is a way to add declarations to the global scope. This is useful when you want to add new functionality to existing libraries or to augment the built-in types in TypeScript.
Here's an example of how you can use global augmentation in TypeScript:
```
// myModule.d.ts
declare namespace NodeJS {
interface Global {
myGlobalFunction(): void;
}
}
// main.ts
global.myGlobalFunction = function () {
console.log("I am a global function!");
};
myGlobalFunction(); // Output: "I am a global function!"
```
In this example, we declare a new namespace "NodeJS" and add an interface "Global" to it. Within the "Global" interface, we declare a new function "myGlobalFunction".
Learn more from the following links:
- [Global augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation)

View File

@@ -1 +1,30 @@
# Modules
# Modules
In TypeScript, modules are used to organize and reuse code. There are two types of modules in TypeScript:
- Internal
- External
Internal modules are used to organize code within a file and are also referred to as namespaces. They are defined using the "namespace" keyword.
External modules are used to organize code across multiple files. They are defined using the "export" keyword in one file and the "import" keyword in another file. External modules in TypeScript follow the CommonJS or ES modules standards.
Here is an example of how you can use internal modules in TypeScript:
```
// myModule.ts
namespace MyModule {
export function doSomething() {
console.log("Doing something...");
}
}
// main.ts
/// <reference path="myModule.ts" />
MyModule.doSomething(); // Output: "Doing something..."
```
Learn more from the following links:
- [Modules](https://www.typescriptlang.org/docs/handbook/modules.html#handbook-content)
- [TypeScript - Modules](https://www.youtube.com/watch?v=EpOPR03z4Vw)

View File

@@ -1 +1,20 @@
# 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.
Here's an example of basic formatting in TypeScript:
```
function add(a: number, b: number): number {
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)

View File

@@ -1 +1,32 @@
# Linting
# Linting
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.
Here's an example of how you can use TSLint, a popular TypeScript linter, in your TypeScript project:
```
// 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/)

View File

@@ -1 +1,49 @@
# 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:
1. Lodash: A utility library that provides a wide range of helpful functions for working with arrays, objects, and other data structures.
```
// Step 1: Install Lodash
npm install lodash
// Step 2: Import Lodash in your TypeScript code
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.

View File

@@ -1 +1,13 @@
# 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:
- Webpack: A popular module bundler that can compile and bundle TypeScript code, as well as other assets such as CSS, images, and 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:
- [Integrating with Build Tools](https://www.typescriptlang.org/docs/handbook/integrating-with-build-tools.html#handbook-content)
- [TypeScript Build Tools](https://www.javatpoint.com/typescript-build-tools)

View File

@@ -1 +1,24 @@
# 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:
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)