mirror of
https://github.com/LeCoupa/awesome-cheatsheets.git
synced 2026-05-02 20:49:59 -07:00
Compare commits
4 Commits
master
..
07d65e22cb
| Author | SHA1 | Date | |
|---|---|---|---|
| 07d65e22cb | |||
| 7f1144c56a | |||
| 8840648ff4 | |||
| 52d590f1c3 |
@@ -1,29 +1,17 @@
|
||||
<div align="center">
|
||||
|
||||
[](https://lecoupa.github.io/awesome-cheatsheets/)
|
||||
|
||||
<a href="https://trendshift.io/repositories/5584" target="_blank">
|
||||
<img src="https://trendshift.io/api/badge/repositories/5584" alt="LeCoupa%2Fawesome-cheatsheets | Trendshift" width="250" height="55"/>
|
||||
</a>
|
||||
|
||||
[](https://awesome.re) [](https://github.com/LeCoupa/awesome-cheatsheets/blob/master/LICENSE)
|
||||
|
||||
**WEBSITE DIRECTORY**: [Available here](https://lecoupa.github.io/awesome-cheatsheets/)
|
||||
**WEBSITE DIRECTORY**: [Available here](https://lecoupa.github.io/awesome-cheatsheets/).
|
||||
|
||||
> 📚 Awesome cheatsheets for popular programming languages, frameworks and development tools. They include everything you should know in one single file.
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 🤔 Why Awesome-Cheatsheets?
|
||||
|
||||
I usually make a cheat sheet when I want to improve my skills in a programming language, a framework or a development tool. [I started doing these kinds of things a long time ago on Gist](https://gist.github.com/LeCoupa). To better keep track of the history and to let people contribute, I re-organized all of them into this single repository. Most of the content is coming from official documentation and some books I have read.
|
||||
|
||||
Feel free to take a look. You might learn new things. They have been designed to provide a quick way to assess your knowledge and to save you time.
|
||||
|
||||
---
|
||||
|
||||
## 📚 Table of Contents
|
||||
|
||||
### 📃 Languages
|
||||
@@ -32,60 +20,59 @@ Feel free to take a look. You might learn new things. They have been designed to
|
||||
<summary>View cheatsheets</summary>
|
||||
|
||||
#### Command line interface
|
||||
|
||||
- [Bash](languages/bash.sh)
|
||||
|
||||
#### Imperative
|
||||
|
||||
- [C](languages/C.txt)
|
||||
- [C#](languages/C%23.txt)
|
||||
- [Go](languages/golang.md)
|
||||
- [Java](languages/java.md)
|
||||
- [PHP](languages/php.php)
|
||||
- [Python](languages/python.md)
|
||||
- [XML](languages/XML.md)
|
||||
|
||||
#### Functional
|
||||
|
||||
- [JavaScript](languages/javascript.js)
|
||||
- [Typescript](languages/typescript.md)
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### 📦 Backend
|
||||
|
||||
<details>
|
||||
<summary>View cheatsheets</summary>
|
||||
|
||||
#### PHP
|
||||
|
||||
- [Laravel](backend/laravel.php)
|
||||
|
||||
#### Python
|
||||
|
||||
- [Django](backend/django.py)
|
||||
|
||||
#### JavaScript
|
||||
#### Javascript
|
||||
|
||||
- [Adonis.js](backend/adonis.js)
|
||||
- [Express.js](backend/express.js)
|
||||
- [Feathers.js](backend/feathers.js)
|
||||
- [Moleculer](backend/moleculer.js)
|
||||
- [Node.js](backend/node.js)
|
||||
- [Sails.js](backend/sails.js)
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
|
||||
### 🌐 Frontend
|
||||
|
||||
<details>
|
||||
<summary>View cheatsheets</summary>
|
||||
|
||||
#### Basics
|
||||
|
||||
- [HTML5](frontend/html5.html)
|
||||
- [CSS3](frontend/css3.css)
|
||||
- [Typescript](frontend/typescript.ts)
|
||||
|
||||
#### Frameworks
|
||||
|
||||
- [React.js](frontend/react.js)
|
||||
- [Vue.js](frontend/vue.js)
|
||||
- [Tailwind.css](frontend/tailwind.css)
|
||||
@@ -94,30 +81,27 @@ Feel free to take a look. You might learn new things. They have been designed to
|
||||
- [AngularJS](frontend/angularjs.js)
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### 🗃️ Databases
|
||||
|
||||
<details>
|
||||
<summary>View cheatsheets</summary>
|
||||
|
||||
#### SQL
|
||||
|
||||
- [MySQL](databases/mysql.sh)
|
||||
|
||||
#### NoSQL
|
||||
- [MongoDB](databases/mongodb.sh)
|
||||
|
||||
- [Redis](databases/redis.sh)
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### 🔧 Tools
|
||||
|
||||
<details>
|
||||
<summary>View cheatsheets</summary>
|
||||
|
||||
#### Development
|
||||
|
||||
- [cURL](tools/curl.sh)
|
||||
- [Drush](tools/drush.sh)
|
||||
- [Elasticsearch](tools/elasticsearch.js)
|
||||
@@ -130,35 +114,25 @@ Feel free to take a look. You might learn new things. They have been designed to
|
||||
- [Xcode](tools/xcode.txt)
|
||||
|
||||
#### Infrastructure
|
||||
|
||||
- [AWS CLI](tools/aws.sh)
|
||||
- [Docker](tools/docker.sh)
|
||||
- [GCP CLI](tools/gcp.md)
|
||||
- [Heroku CLI](tools/heroku.sh)
|
||||
- [Kubernetes](tools/kubernetes.md)
|
||||
- [macOS](tools/macos.sh)
|
||||
- [Nanobox Boxfile](tools/nanobox_boxfile.yml)
|
||||
- [Nanobox CLI](tools/nanobox_cli.sh)
|
||||
- [Nginx](tools/nginx.sh)
|
||||
- [PM2](tools/pm2.sh)
|
||||
- [Ubuntu](tools/ubuntu.sh)
|
||||
- [Firebase CLI](tools/firebase_cli.md)
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 🙌🏼 How to Contribute?
|
||||
|
||||
You are more than welcome to contribute and build your own cheat sheet for your favorite programming language, framework or development tool. Just submit changes via pull request and I will review them before merging.
|
||||
|
||||
---
|
||||
|
||||
## 👩💻👨💻 Our valuable Contributors
|
||||
|
||||
<div align="center">
|
||||
|
||||
<a href="https://github.com/LeCoupa/awesome-cheatsheets/graphs/contributors">
|
||||
<p align="center"><a href="https://github.com/LeCoupa/awesome-cheatsheets/graphs/contributors">
|
||||
<img src="https://contributors-img.web.app/image?repo=LeCoupa/awesome-cheatsheets" />
|
||||
</a>
|
||||
|
||||
</div>
|
||||
</a></p>
|
||||
|
||||
@@ -82,33 +82,3 @@ SELECT User, Host FROM mysql.user; # List all current MySQL users
|
||||
|
||||
SET GLOBAL general_log = 'ON'; # Enable query logging
|
||||
SHOW FULL PROCESSLIST; # Show the last queries executed in MySQL
|
||||
|
||||
# *****************************************************************************
|
||||
# Altering Table Structure
|
||||
# *****************************************************************************
|
||||
|
||||
ALTER TABLE table_name ADD COLUMN column_name datatype; # Add a new column to an existing table
|
||||
ALTER TABLE table_name MODIFY COLUMN column_name datatype; # Change the data type of a column
|
||||
ALTER TABLE table_name RENAME COLUMN old_name TO new_name; # Rename a column (MySQL 8.0+)
|
||||
ALTER TABLE table_name DROP COLUMN column_name; # Remove a column from a table
|
||||
ALTER TABLE old_table_name RENAME TO new_table_name; # Rename an entire table
|
||||
|
||||
# *****************************************************************************
|
||||
# Indexes (Performance Tuning)
|
||||
# *****************************************************************************
|
||||
|
||||
CREATE INDEX idx_name ON table_name (column_name); # Create a standard index to speed up queries
|
||||
CREATE UNIQUE INDEX idx_name ON table_name (column_name); # Create a unique index (no duplicate values)
|
||||
SHOW INDEX FROM table_name; # List all indexes on a specific table
|
||||
DROP INDEX idx_name ON table_name; # Remove an index from a table
|
||||
EXPLAIN SELECT * FROM table_name WHERE condition; # Analyze how MySQL executes a query (Check index usage)
|
||||
|
||||
# *****************************************************************************
|
||||
# Transactions (Data Integrity)
|
||||
# *****************************************************************************
|
||||
|
||||
START TRANSACTION; # Begin a new transaction
|
||||
COMMIT; # Save all changes made during the transaction
|
||||
ROLLBACK; # Undo all changes if an error occurs before commit
|
||||
SET AUTOCOMMIT = 0; # Disable automatic commits for the current session
|
||||
SET AUTOCOMMIT = 1; # Re-enable automatic commits after finishing manual transactions
|
||||
|
||||
+47
-71
@@ -43,14 +43,11 @@
|
||||
|
||||
.hidden /* display: none; */
|
||||
.block /* display: block; */
|
||||
.flow-root /* display: flow-root; */
|
||||
.inline-block /* display: inline-block; */
|
||||
.inline /* display: inline; */
|
||||
.flex /* display: flex; */
|
||||
.inline-flex /* display: inline-flex; */
|
||||
.grid /* display: grid; */
|
||||
.inline-grid /* display: inline-grid; */
|
||||
.contents /* display: contents; */
|
||||
.table /* display: table; */
|
||||
.table-caption /* display: table-caption; */
|
||||
.table-cell /* display: table-cell; */
|
||||
@@ -71,6 +68,7 @@
|
||||
.float-right /* float: right; */
|
||||
.float-left /* float: left; */
|
||||
.float-none /* float: none; */
|
||||
.clearfix /* &::after { content: ""; display: table; clear: both; } */
|
||||
|
||||
/*
|
||||
* Clear
|
||||
@@ -132,6 +130,8 @@
|
||||
.overflow-y-visible /* overflow-y: visible; */
|
||||
.overflow-x-scroll /* overflow-x: scroll; */
|
||||
.overflow-y-scroll /* overflow-y: scroll; */
|
||||
.scrolling-touch /* -webkit-overflow-scrolling: touch; */
|
||||
.scrolling-auto /* -webkit-overflow-scrolling: auto; */
|
||||
|
||||
/*
|
||||
* Position
|
||||
@@ -219,7 +219,7 @@
|
||||
* By default, only responsive variants are generated for flex-wrap utilities.
|
||||
*/
|
||||
|
||||
.flex-nowrap /* flex-wrap: nowrap; */
|
||||
.flex-no-wrap /* flex-wrap: nowrap; */
|
||||
.flex-wrap /* flex-wrap: wrap; */
|
||||
.flex-wrap-reverse /* flex-wrap: wrap-reverse; */
|
||||
|
||||
@@ -478,44 +478,44 @@
|
||||
.gap-56 /* gap: 14rem; */
|
||||
.gap-64 /* gap: 16rem; */
|
||||
.gap-px /* gap: 1px; */
|
||||
.gap-y-0 /* row-gap: 0; */
|
||||
.gap-y-1 /* row-gap: 0.25rem; */
|
||||
.gap-y-2 /* row-gap: 0.5rem; */
|
||||
.gap-y-3 /* row-gap: 0.75rem; */
|
||||
.gap-y-4 /* row-gap: 1rem; */
|
||||
.gap-y-5 /* row-gap: 1.25rem; */
|
||||
.gap-y-6 /* row-gap: 1.5rem; */
|
||||
.gap-y-8 /* row-gap: 2rem; */
|
||||
.gap-y-10 /* row-gap: 2.5rem; */
|
||||
.gap-y-12 /* row-gap: 3rem; */
|
||||
.gap-y-16 /* row-gap: 4rem; */
|
||||
.gap-y-20 /* row-gap: 5rem; */
|
||||
.gap-y-24 /* row-gap: 6rem; */
|
||||
.gap-y-32 /* row-gap: 8rem; */
|
||||
.gap-y-40 /* row-gap: 10rem; */
|
||||
.gap-y-48 /* row-gap: 12rem; */
|
||||
.gap-y-56 /* row-gap: 14rem; */
|
||||
.gap-y-64 /* row-gap: 16rem; */
|
||||
.gap-y-px /* row-gap: 1px; */
|
||||
.gap-x-0 /* column-gap: 0; */
|
||||
.gap-x-1 /* column-gap: 0.25rem; */
|
||||
.gap-x-2 /* column-gap: 0.5rem; */
|
||||
.gap-x-3 /* column-gap: 0.75rem; */
|
||||
.gap-x-4 /* column-gap: 1rem; */
|
||||
.gap-x-5 /* column-gap: 1.25rem; */
|
||||
.gap-x-6 /* column-gap: 1.5rem; */
|
||||
.gap-x-8 /* column-gap: 2rem; */
|
||||
.gap-x-10 /* column-gap: 2.5rem; */
|
||||
.gap-x-12 /* column-gap: 3rem; */
|
||||
.gap-x-16 /* column-gap: 4rem; */
|
||||
.gap-x-20 /* column-gap: 5rem; */
|
||||
.gap-x-24 /* column-gap: 6rem; */
|
||||
.gap-x-32 /* column-gap: 8rem; */
|
||||
.gap-x-40 /* column-gap: 10rem; */
|
||||
.gap-x-48 /* column-gap: 12rem; */
|
||||
.gap-x-56 /* column-gap: 14rem; */
|
||||
.gap-x-64 /* column-gap: 16rem; */
|
||||
.gap-x-px /* column-gap: 1px; */
|
||||
.row-gap-0 /* row-gap: 0; */
|
||||
.row-gap-1 /* row-gap: 0.25rem; */
|
||||
.row-gap-2 /* row-gap: 0.5rem; */
|
||||
.row-gap-3 /* row-gap: 0.75rem; */
|
||||
.row-gap-4 /* row-gap: 1rem; */
|
||||
.row-gap-5 /* row-gap: 1.25rem; */
|
||||
.row-gap-6 /* row-gap: 1.5rem; */
|
||||
.row-gap-8 /* row-gap: 2rem; */
|
||||
.row-gap-10 /* row-gap: 2.5rem; */
|
||||
.row-gap-12 /* row-gap: 3rem; */
|
||||
.row-gap-16 /* row-gap: 4rem; */
|
||||
.row-gap-20 /* row-gap: 5rem; */
|
||||
.row-gap-24 /* row-gap: 6rem; */
|
||||
.row-gap-32 /* row-gap: 8rem; */
|
||||
.row-gap-40 /* row-gap: 10rem; */
|
||||
.row-gap-48 /* row-gap: 12rem; */
|
||||
.row-gap-56 /* row-gap: 14rem; */
|
||||
.row-gap-64 /* row-gap: 16rem; */
|
||||
.row-gap-px /* row-gap: 1px; */
|
||||
.col-gap-0 /* column-gap: 0; */
|
||||
.col-gap-1 /* column-gap: 0.25rem; */
|
||||
.col-gap-2 /* column-gap: 0.5rem; */
|
||||
.col-gap-3 /* column-gap: 0.75rem; */
|
||||
.col-gap-4 /* column-gap: 1rem; */
|
||||
.col-gap-5 /* column-gap: 1.25rem; */
|
||||
.col-gap-6 /* column-gap: 1.5rem; */
|
||||
.col-gap-8 /* column-gap: 2rem; */
|
||||
.col-gap-10 /* column-gap: 2.5rem; */
|
||||
.col-gap-12 /* column-gap: 3rem; */
|
||||
.col-gap-16 /* column-gap: 4rem; */
|
||||
.col-gap-20 /* column-gap: 5rem; */
|
||||
.col-gap-24 /* column-gap: 6rem; */
|
||||
.col-gap-32 /* column-gap: 8rem; */
|
||||
.col-gap-40 /* column-gap: 10rem; */
|
||||
.col-gap-48 /* column-gap: 12rem; */
|
||||
.col-gap-56 /* column-gap: 14rem; */
|
||||
.col-gap-64 /* column-gap: 16rem; */
|
||||
.col-gap-px /* column-gap: 1px; */
|
||||
|
||||
/*
|
||||
* Grid Auto Flow
|
||||
@@ -1153,8 +1153,8 @@
|
||||
* By default, only responsive, hover and focus variants are generated for font weight utilities.
|
||||
*/
|
||||
|
||||
.font-thin /* font-weight: 100; */
|
||||
.font-extralight /* font-weight: 200; */
|
||||
.font-hairline /* font-weight: 100; */
|
||||
.font-thin /* font-weight: 200; */
|
||||
.font-light /* font-weight: 300; */
|
||||
.font-normal /* font-weight: 400; */
|
||||
.font-medium /* font-weight: 500; */
|
||||
@@ -1479,7 +1479,7 @@
|
||||
*/
|
||||
|
||||
.whitespace-normal /* white-space: normal; */
|
||||
.whitespace-nowrap /* white-space: nowrap; */
|
||||
.whitespace-no-wrap /* white-space: nowrap; */
|
||||
.whitespace-pre /* white-space: pre; */
|
||||
.whitespace-pre-line /* white-space: pre-line; */
|
||||
.whitespace-pre-wrap /* white-space: pre-wrap; */
|
||||
@@ -1902,6 +1902,7 @@
|
||||
* By default, only responsive, hover and focus variants are generated for box shadow utilities.
|
||||
*/
|
||||
|
||||
.shadow-xs /* box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05); */
|
||||
.shadow-sm /* box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); */
|
||||
.shadow /* box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06); */
|
||||
.shadow-md /* box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); */
|
||||
@@ -1909,34 +1910,9 @@
|
||||
.shadow-xl /* box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); */
|
||||
.shadow-2xl /* box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); */
|
||||
.shadow-inner /* box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.06); */
|
||||
.shadow-outline /* box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.5); */
|
||||
.shadow-none /* box-shadow: none; */
|
||||
|
||||
/*
|
||||
* RING
|
||||
* --------------------
|
||||
* Utilities for creating outline rings with box-shadows.
|
||||
* Replaced the old .shadow-outline utility.
|
||||
*/
|
||||
|
||||
.ring-0 /* box-shadow: 0 0 0 0px; */
|
||||
.ring-1 /* box-shadow: 0 0 0 1px; */
|
||||
.ring-2 /* box-shadow: 0 0 0 2px; */
|
||||
.ring-4 /* box-shadow: 0 0 0 4px; */
|
||||
.ring-8 /* box-shadow: 0 0 0 8px; */
|
||||
.ring /* box-shadow: 0 0 0 3px; */
|
||||
.ring-inset /* --ring-inset: inset; */
|
||||
|
||||
.ring-transparent /* --ring-color: transparent; */
|
||||
.ring-black /* --ring-color: #000; */
|
||||
.ring-white /* --ring-color: #fff; */
|
||||
.ring-current /* --ring-color: currentColor; */
|
||||
|
||||
.ring-offset-0 /* --ring-offset-width: 0px; */
|
||||
.ring-offset-1 /* --ring-offset-width: 1px; */
|
||||
.ring-offset-2 /* --ring-offset-width: 2px; */
|
||||
.ring-offset-4 /* --ring-offset-width: 4px; */
|
||||
.ring-offset-8 /* --ring-offset-width: 8px; */
|
||||
|
||||
/*
|
||||
* OPACITY
|
||||
* --------------------
|
||||
|
||||
@@ -1,670 +0,0 @@
|
||||
/****************************
|
||||
* TYPESCRIPT CHEATSHEET - Quick Reference
|
||||
* Learn more: https://www.typescriptlang.org/docs/
|
||||
* Playground: https://www.typescriptlang.org/play
|
||||
* Handbook: https://www.typescriptlang.org/handbook/
|
||||
*
|
||||
* Table of contents
|
||||
* -------------------
|
||||
* 01 | Basic Types
|
||||
* 02 | Variables & Arrays
|
||||
* 03 | Functions
|
||||
* 04 | Objects & Interfaces
|
||||
* 05 | Classes
|
||||
* 06 | Generics
|
||||
* 07 | Union & Literal Types
|
||||
* 08 | Type Guards & Assertions
|
||||
* 09 | Utility Types
|
||||
* 10 | Enums
|
||||
* 11 | Modules
|
||||
* 12 | Advanced Types
|
||||
* 13 | Decorators
|
||||
* 14 | Configuration
|
||||
* 15 | Common Patterns
|
||||
*****************************/
|
||||
|
||||
/***************************
|
||||
------------ 01: Basic Types -----------
|
||||
*******************************/
|
||||
|
||||
// Primitive Types
|
||||
let str: string = "hello";
|
||||
let num: number = 42;
|
||||
let bool: boolean = true;
|
||||
let undef: undefined = undefined;
|
||||
let nul: null = null;
|
||||
|
||||
// Special Types
|
||||
let anything: any = "can be anything";
|
||||
let unknown: unknown = "type-safe any";
|
||||
let nothing: void = undefined;
|
||||
let never: never = (() => { throw new Error() })();
|
||||
|
||||
// Type Inference
|
||||
let auto = "TypeScript infers string";
|
||||
let nums = [1, 2, 3]; // number[]
|
||||
|
||||
/***************************
|
||||
------------ 02: Variables & Arrays -----------
|
||||
*******************************/
|
||||
|
||||
// Arrays
|
||||
let numbers: number[] = [1, 2, 3];
|
||||
let strings: Array<string> = ["a", "b"];
|
||||
let mixed: (string | number)[] = [1, "two"];
|
||||
|
||||
// Tuples
|
||||
let tuple: [string, number] = ["hello", 42];
|
||||
let namedTuple: [name: string, age: number] = ["John", 30];
|
||||
|
||||
// Destructuring
|
||||
let [first, second] = tuple;
|
||||
let [x, y, ...rest] = [1, 2, 3, 4, 5];
|
||||
|
||||
// Object Destructuring
|
||||
let {name, age} = {name: "John", age: 30};
|
||||
let {a: newName, b = 10} = {a: "value"}; // rename & default
|
||||
|
||||
/***************************
|
||||
------------ 03: Functions -----------
|
||||
*******************************/
|
||||
|
||||
// Function Declaration
|
||||
function add(x: number, y: number): number {
|
||||
return x + y;
|
||||
}
|
||||
|
||||
// Arrow Functions
|
||||
const multiply = (x: number, y: number): number => x * y;
|
||||
const greet = (name: string): void => console.log(`Hello ${name}`);
|
||||
|
||||
// Optional & Default Parameters
|
||||
function build(first: string, last?: string, age = 25): string {
|
||||
return `${first} ${last || ""} (${age})`;
|
||||
}
|
||||
|
||||
// Rest Parameters
|
||||
function sum(...nums: number[]): number {
|
||||
return nums.reduce((a, b) => a + b, 0);
|
||||
}
|
||||
|
||||
// Function Overloads
|
||||
function format(x: string): string;
|
||||
function format(x: number): string;
|
||||
function format(x: string | number): string {
|
||||
return x.toString();
|
||||
}
|
||||
|
||||
// Function Types
|
||||
type MathOp = (x: number, y: number) => number;
|
||||
const divide: MathOp = (x, y) => x / y;
|
||||
|
||||
/***************************
|
||||
------------ 04: Objects & Interfaces -----------
|
||||
*******************************/
|
||||
|
||||
// Object Types
|
||||
let person: {name: string, age: number} = {name: "John", age: 30};
|
||||
|
||||
// Interface
|
||||
interface User {
|
||||
readonly id: number;
|
||||
name: string;
|
||||
email?: string; // optional
|
||||
[key: string]: any; // index signature
|
||||
}
|
||||
|
||||
// Extending Interfaces
|
||||
interface Admin extends User {
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
// Multiple Inheritance
|
||||
interface Timestamped {
|
||||
createdAt: Date;
|
||||
}
|
||||
interface AdminUser extends User, Timestamped {
|
||||
role: "admin";
|
||||
}
|
||||
|
||||
// Function in Interface
|
||||
interface Calculator {
|
||||
add(x: number, y: number): number;
|
||||
subtract: (x: number, y: number) => number;
|
||||
}
|
||||
|
||||
/***************************
|
||||
------------ 05: Classes -----------
|
||||
*******************************/
|
||||
|
||||
// Basic Class
|
||||
class Animal {
|
||||
public name: string;
|
||||
private age: number;
|
||||
protected species: string;
|
||||
readonly id: number;
|
||||
|
||||
constructor(name: string, age: number) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.species = "unknown";
|
||||
this.id = Math.random();
|
||||
}
|
||||
|
||||
speak(): void {
|
||||
console.log(`${this.name} makes a sound`);
|
||||
}
|
||||
}
|
||||
|
||||
// Inheritance
|
||||
class Dog extends Animal {
|
||||
breed: string;
|
||||
|
||||
constructor(name: string, age: number, breed: string) {
|
||||
super(name, age);
|
||||
this.breed = breed;
|
||||
}
|
||||
|
||||
speak(): void {
|
||||
console.log(`${this.name} barks`);
|
||||
}
|
||||
}
|
||||
|
||||
// Abstract Class
|
||||
abstract class Shape {
|
||||
abstract area(): number;
|
||||
|
||||
display(): void {
|
||||
console.log(`Area: ${this.area()}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Static Members
|
||||
class MathUtils {
|
||||
static PI = 3.14159;
|
||||
static circle(radius: number): number {
|
||||
return 2 * MathUtils.PI * radius;
|
||||
}
|
||||
}
|
||||
|
||||
// Getters/Setters
|
||||
class Person {
|
||||
private _age: number = 0;
|
||||
|
||||
get age(): number {
|
||||
return this._age;
|
||||
}
|
||||
|
||||
set age(value: number) {
|
||||
if (value >= 0) this._age = value;
|
||||
}
|
||||
}
|
||||
|
||||
/***************************
|
||||
------------ 06: Generics -----------
|
||||
*******************************/
|
||||
|
||||
// Generic Functions
|
||||
function identity<T>(arg: T): T { return arg; }
|
||||
const result = identity<string>("hello");
|
||||
const inferred = identity(42); // T inferred as number
|
||||
|
||||
// Multiple Type Parameters
|
||||
function pair<T, U>(first: T, second: U): [T, U] {
|
||||
return [first, second];
|
||||
}
|
||||
|
||||
// Generic Interface
|
||||
interface Container<T> {
|
||||
value: T;
|
||||
getValue(): T;
|
||||
}
|
||||
|
||||
// Generic Class
|
||||
class Box<T> {
|
||||
contents: T;
|
||||
constructor(value: T) {
|
||||
this.contents = value;
|
||||
}
|
||||
}
|
||||
|
||||
// Constraints
|
||||
interface HasLength {
|
||||
length: number;
|
||||
}
|
||||
|
||||
function logLength<T extends HasLength>(arg: T): void {
|
||||
console.log(arg.length);
|
||||
}
|
||||
|
||||
// Keyof Constraint
|
||||
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
|
||||
return obj[key];
|
||||
}
|
||||
|
||||
/***************************
|
||||
------------ 07: Union & Literal Types -----------
|
||||
*******************************/
|
||||
|
||||
// Union Types
|
||||
type StringOrNumber = string | number;
|
||||
type Status = "loading" | "success" | "error";
|
||||
|
||||
function process(id: string | number): void {
|
||||
if (typeof id === "string") {
|
||||
console.log(id.toUpperCase());
|
||||
} else {
|
||||
console.log(id.toFixed(2));
|
||||
}
|
||||
}
|
||||
|
||||
// Intersection Types
|
||||
type Person = {name: string};
|
||||
type Employee = {company: string};
|
||||
type Staff = Person & Employee; // has both properties
|
||||
|
||||
// Literal Types
|
||||
type Theme = "light" | "dark";
|
||||
type Port = 3000 | 8080 | 9000;
|
||||
type Success = true;
|
||||
|
||||
// Discriminated Unions
|
||||
interface Circle {
|
||||
kind: "circle";
|
||||
radius: number;
|
||||
}
|
||||
interface Square {
|
||||
kind: "square";
|
||||
sideLength: number;
|
||||
}
|
||||
type Shape = Circle | Square;
|
||||
|
||||
function area(shape: Shape): number {
|
||||
switch (shape.kind) {
|
||||
case "circle":
|
||||
return Math.PI * shape.radius ** 2;
|
||||
case "square":
|
||||
return shape.sideLength ** 2;
|
||||
}
|
||||
}
|
||||
|
||||
/***************************
|
||||
------------ 08: Type Guards & Assertions -----------
|
||||
*******************************/
|
||||
|
||||
// Type Guards
|
||||
function isString(value: any): value is string {
|
||||
return typeof value === "string";
|
||||
}
|
||||
|
||||
function isNumber(value: any): value is number {
|
||||
return typeof value === "number";
|
||||
}
|
||||
|
||||
// Using Type Guards
|
||||
function process(value: string | number) {
|
||||
if (isString(value)) {
|
||||
console.log(value.toUpperCase()); // TypeScript knows it's string
|
||||
} else {
|
||||
console.log(value.toFixed(2)); // TypeScript knows it's number
|
||||
}
|
||||
}
|
||||
|
||||
// in operator
|
||||
type Fish = { swim: () => void };
|
||||
type Bird = { fly: () => void };
|
||||
|
||||
function move(animal: Fish | Bird) {
|
||||
if ("swim" in animal) {
|
||||
animal.swim(); // Fish
|
||||
} else {
|
||||
animal.fly(); // Bird
|
||||
}
|
||||
}
|
||||
|
||||
// instanceof
|
||||
function handleError(error: Error | string) {
|
||||
if (error instanceof Error) {
|
||||
console.log(error.message);
|
||||
} else {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
// Type Assertions
|
||||
let someValue: any = "hello world";
|
||||
let strLength = (someValue as string).length;
|
||||
// or: let strLength = (<string>someValue).length;
|
||||
|
||||
// Non-null Assertion
|
||||
let name: string | null = getName();
|
||||
let nameLength = name!.length; // Assert name is not null
|
||||
|
||||
/***************************
|
||||
------------ 09: Utility Types -----------
|
||||
*******************************/
|
||||
|
||||
interface Todo {
|
||||
title: string;
|
||||
description: string;
|
||||
completed: boolean;
|
||||
}
|
||||
|
||||
// Partial<T> - All properties optional
|
||||
type PartialTodo = Partial<Todo>;
|
||||
// {title?: string, description?: string, completed?: boolean}
|
||||
|
||||
// Required<T> - All properties required
|
||||
type RequiredTodo = Required<PartialTodo>;
|
||||
|
||||
// Readonly<T> - All properties readonly
|
||||
type ReadonlyTodo = Readonly<Todo>;
|
||||
|
||||
// Pick<T, K> - Select specific properties
|
||||
type TodoPreview = Pick<Todo, "title" | "completed">;
|
||||
|
||||
// Omit<T, K> - Exclude specific properties
|
||||
type TodoInfo = Omit<Todo, "completed">;
|
||||
|
||||
// Record<K, T> - Create object type
|
||||
type TodoStatus = Record<"pending" | "completed", Todo[]>;
|
||||
|
||||
// Exclude<T, U> - Remove types from union
|
||||
type NonString = Exclude<string | number | boolean, string>;
|
||||
// number | boolean
|
||||
|
||||
// Extract<T, U> - Extract types from union
|
||||
type StringOnly = Extract<string | number | boolean, string>;
|
||||
// string
|
||||
|
||||
// NonNullable<T> - Remove null/undefined
|
||||
type NonNullString = NonNullable<string | null | undefined>;
|
||||
// string
|
||||
|
||||
// ReturnType<T> - Get function return type
|
||||
function getName(): string { return "John"; }
|
||||
type NameType = ReturnType<typeof getName>; // string
|
||||
|
||||
// Parameters<T> - Get function parameters as tuple
|
||||
type GetNameParams = Parameters<typeof getName>; // []
|
||||
|
||||
/***************************
|
||||
------------ 10: Enums -----------
|
||||
*******************************/
|
||||
|
||||
// Numeric Enum
|
||||
enum Direction {
|
||||
Up, // 0
|
||||
Down, // 1
|
||||
Left, // 2
|
||||
Right // 3
|
||||
}
|
||||
|
||||
// String Enum
|
||||
enum Color {
|
||||
Red = "red",
|
||||
Green = "green",
|
||||
Blue = "blue"
|
||||
}
|
||||
|
||||
// Mixed Enum
|
||||
enum Mixed {
|
||||
No = 0,
|
||||
Yes = "yes"
|
||||
}
|
||||
|
||||
// Const Enum (inlined at compile time)
|
||||
const enum StatusCode {
|
||||
OK = 200,
|
||||
NotFound = 404,
|
||||
Error = 500
|
||||
}
|
||||
|
||||
// Usage
|
||||
let currentDirection = Direction.Up;
|
||||
let favoriteColor = Color.Blue;
|
||||
let status = StatusCode.OK;
|
||||
|
||||
/***************************
|
||||
------------ 11: Modules -----------
|
||||
*******************************/
|
||||
|
||||
// Named Exports
|
||||
export const PI = 3.14159;
|
||||
export function calculate(r: number): number {
|
||||
return PI * r * r;
|
||||
}
|
||||
export class Calculator {
|
||||
add(x: number, y: number): number { return x + y; }
|
||||
}
|
||||
|
||||
// Default Export
|
||||
export default class Logger {
|
||||
log(message: string): void {
|
||||
console.log(message);
|
||||
}
|
||||
}
|
||||
|
||||
// Re-exports
|
||||
export { Calculator as Calc } from "./calculator";
|
||||
export * from "./utilities";
|
||||
|
||||
// Import
|
||||
import Logger from "./logger"; // default import
|
||||
import { PI, calculate } from "./math"; // named imports
|
||||
import * as MathUtils from "./math"; // namespace import
|
||||
import { Calculator as Calc } from "./calculator"; // alias
|
||||
|
||||
// Dynamic Imports
|
||||
const module = await import("./dynamic-module");
|
||||
|
||||
/***************************
|
||||
------------ 12: Advanced Types -----------
|
||||
*******************************/
|
||||
|
||||
// Mapped Types
|
||||
type Nullable<T> = {
|
||||
[P in keyof T]: T[P] | null;
|
||||
};
|
||||
|
||||
type OptionalId<T> = {
|
||||
[P in keyof T]: P extends "id" ? T[P] | undefined : T[P];
|
||||
};
|
||||
|
||||
// Conditional Types
|
||||
type IsString<T> = T extends string ? true : false;
|
||||
type StringCheck = IsString<"hello">; // true
|
||||
|
||||
// Template Literal Types
|
||||
type EventName<T extends string> = `on${Capitalize<T>}`;
|
||||
type ClickEvent = EventName<"click">; // "onClick"
|
||||
|
||||
// Indexed Access Types
|
||||
type Person = { name: string; age: number; location: string };
|
||||
type PersonName = Person["name"]; // string
|
||||
type PersonKeys = keyof Person; // "name" | "age" | "location"
|
||||
|
||||
// Recursive Types
|
||||
type Json = string | number | boolean | null | Json[] | {[key: string]: Json};
|
||||
|
||||
/***************************
|
||||
------------ 13: Decorators -----------
|
||||
*******************************/
|
||||
|
||||
// Class Decorator
|
||||
function Component(name: string) {
|
||||
return function<T extends {new(...args: any[]): {}}>(constructor: T) {
|
||||
return class extends constructor {
|
||||
componentName = name;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@Component("MyComponent")
|
||||
class MyClass {}
|
||||
|
||||
// Method Decorator
|
||||
function Log(target: any, propertyName: string, descriptor: PropertyDescriptor) {
|
||||
const method = descriptor.value;
|
||||
descriptor.value = function(...args: any[]) {
|
||||
console.log(`Calling ${propertyName} with`, args);
|
||||
return method.apply(this, args);
|
||||
};
|
||||
}
|
||||
|
||||
class Service {
|
||||
@Log
|
||||
getData(): string {
|
||||
return "data";
|
||||
}
|
||||
}
|
||||
|
||||
// Property Decorator
|
||||
function MinLength(length: number) {
|
||||
return function(target: any, propertyName: string) {
|
||||
let value: string;
|
||||
|
||||
const getter = () => value;
|
||||
const setter = (newVal: string) => {
|
||||
if (newVal.length < length) {
|
||||
throw new Error(`${propertyName} must be at least ${length} chars`);
|
||||
}
|
||||
value = newVal;
|
||||
};
|
||||
|
||||
Object.defineProperty(target, propertyName, {
|
||||
get: getter,
|
||||
set: setter
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
class User {
|
||||
@MinLength(3)
|
||||
username: string;
|
||||
}
|
||||
|
||||
/***************************
|
||||
------------ 14: Configuration -----------
|
||||
*******************************/
|
||||
|
||||
// tsconfig.json
|
||||
/*
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2020", "DOM"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"moduleResolution": "node",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"sourceMap": true,
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"noImplicitAny": true,
|
||||
"noImplicitReturns": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
*/
|
||||
|
||||
// Compiler Options Quick Reference
|
||||
// --target: ES5, ES6, ES2017, ES2018, ES2019, ES2020, ESNext
|
||||
// --module: commonjs, amd, es2015, es2020, esnext, system, umd
|
||||
// --lib: ES5, ES6, ES2017, DOM, WebWorker, ScriptHost
|
||||
// --strict: Enable all strict type checking options
|
||||
|
||||
/***************************
|
||||
------------ 15: Common Patterns -----------
|
||||
*******************************/
|
||||
|
||||
// API Response Type
|
||||
interface ApiResponse<T> {
|
||||
data: T;
|
||||
status: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
// Event Handler Pattern
|
||||
type EventHandler<T = Event> = (event: T) => void;
|
||||
const onClick: EventHandler<MouseEvent> = (e) => console.log(e.clientX);
|
||||
|
||||
// Builder Pattern
|
||||
class QueryBuilder {
|
||||
private query = "";
|
||||
|
||||
select(fields: string): this {
|
||||
this.query += `SELECT ${fields} `;
|
||||
return this;
|
||||
}
|
||||
|
||||
from(table: string): this {
|
||||
this.query += `FROM ${table} `;
|
||||
return this;
|
||||
}
|
||||
|
||||
build(): string {
|
||||
return this.query.trim();
|
||||
}
|
||||
}
|
||||
|
||||
// Factory Pattern
|
||||
interface Shape { area(): number; }
|
||||
class Circle implements Shape {
|
||||
constructor(private radius: number) {}
|
||||
area(): number { return Math.PI * this.radius ** 2; }
|
||||
}
|
||||
|
||||
class ShapeFactory {
|
||||
static createCircle(radius: number): Shape {
|
||||
return new Circle(radius);
|
||||
}
|
||||
}
|
||||
|
||||
// Promise/Async Patterns
|
||||
type AsyncResult<T> = Promise<T | Error>;
|
||||
|
||||
async function fetchUser(id: number): Promise<User | null> {
|
||||
try {
|
||||
const response = await fetch(`/api/users/${id}`);
|
||||
return await response.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Type-safe Environment Variables
|
||||
interface Env {
|
||||
NODE_ENV: "development" | "production" | "test";
|
||||
PORT: number;
|
||||
DATABASE_URL: string;
|
||||
}
|
||||
|
||||
declare global {
|
||||
namespace NodeJS {
|
||||
interface ProcessEnv extends Env {}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* QUICK TIPS
|
||||
* ----------
|
||||
* • Use 'unknown' instead of 'any' when possible
|
||||
* • Prefer 'interface' for object shapes, 'type' for unions/computed types
|
||||
* • Enable strict mode in tsconfig.json
|
||||
* • Use const assertions: const colors = ['red', 'blue'] as const
|
||||
* • Prefer type guards over type assertions
|
||||
* • Use utility types instead of manual type manipulation
|
||||
* • Enable noImplicitAny for better type safety
|
||||
* • Use discriminated unions for complex state management
|
||||
*/
|
||||
@@ -0,0 +1,479 @@
|
||||
CHEATSHEET HASKELL
|
||||
|
||||
Use HASKELL
|
||||
|
||||
Documentation
|
||||
- Haskell API search: http://www.haskell.org/hoogle/
|
||||
- Haskell reference: ftp://ftpdeveloppez.com/cmaneu/langages/haskell/haskellreference.zip
|
||||
|
||||
Basics
|
||||
- Load file :load filename
|
||||
- Reload file :reload
|
||||
- Launch file editor with current file :edit
|
||||
- Get information about a function :info command
|
||||
|
||||
Comments
|
||||
|
||||
A single line comment starts with ‘--’ and extends to the end of the line.
|
||||
Multi-line comments start with ’{-’ and extend to ’-}’. Comments can be nested.
|
||||
|
||||
Reserved words
|
||||
|
||||
!
|
||||
'
|
||||
''
|
||||
-
|
||||
--
|
||||
-<
|
||||
-<<
|
||||
->
|
||||
::
|
||||
;
|
||||
<-
|
||||
,
|
||||
=
|
||||
=>
|
||||
>
|
||||
?
|
||||
#
|
||||
*
|
||||
@
|
||||
[|, |]
|
||||
\
|
||||
_
|
||||
`
|
||||
{, }
|
||||
{-, -}
|
||||
|
|
||||
~
|
||||
as
|
||||
case, of
|
||||
class
|
||||
data
|
||||
data family
|
||||
data instance
|
||||
default
|
||||
deriving
|
||||
deriving instance
|
||||
do
|
||||
forall
|
||||
foreign
|
||||
hiding
|
||||
if, then, else
|
||||
import
|
||||
infix, infixl, infixr
|
||||
instance
|
||||
let, in
|
||||
mdo
|
||||
module
|
||||
newtype
|
||||
proc
|
||||
qualified
|
||||
rec
|
||||
type
|
||||
type family
|
||||
type instance
|
||||
where
|
||||
|
||||
Data types
|
||||
|
||||
All the data types must start by a capital letter.
|
||||
|
||||
Int: Integer number with fixed precision
|
||||
Integer: Integer number with virtually no limits
|
||||
Float: Real floating point with single precision
|
||||
Double: Real floating point with double the precision
|
||||
Bool: Boolean
|
||||
Char: Character, have to placed between quotes
|
||||
String: A list of Chars
|
||||
|
||||
Type redefinition
|
||||
Type NewTypeName = TypeValue
|
||||
Example: Type String = [Char]
|
||||
|
||||
List & Numbers
|
||||
|
||||
[] – Empty list
|
||||
[1,2,3,4] – List of four numbers
|
||||
1 : 2 : 3 : 4 : [] - Write a lists using cons (:) and nil ([])
|
||||
[1..100] - List of number 1,2,3..,100
|
||||
[100..] - Infinite list of number 100,101,102,103,..
|
||||
[0,-1 ..] - Negative integers 0,-1,-2,..
|
||||
(h:q) - h stands for the first element of the list and q for the result
|
||||
(f:s:t:q) - f is the first element, s is the second elemnt, t is the third and q is the rest of the elements of the list.
|
||||
|
||||
It can be added the element e to the list l with e:l
|
||||
|
||||
Basic functions for lists
|
||||
|
||||
list1++list2 append two list
|
||||
list!!n return element n
|
||||
head takes a list and returns its head. The head of a list is basically its first element.
|
||||
tail takes a list and returns its tail. In other words, it chops off a list's head.
|
||||
last takes a list and returns its last element.
|
||||
init takes a list and returns everything except its last element.
|
||||
length takes a list and returns its length, obviously.
|
||||
null checks if a list is empty.
|
||||
reverse reverses a list.
|
||||
take takes number and a list. It extracts that many elements from the beginning of the list.
|
||||
drop works in a similar way as take, only it drops the number of elements from the beginning of a list.
|
||||
maximum takes a list of stuff that can be put in some kind of order and returns the biggest element.
|
||||
minimum returns the smallest.
|
||||
sum takes a list of numbers and returns their sum.
|
||||
product takes a list of numbers and returns their product.
|
||||
elem takes a thing and a list of things and tells us if that thing is an element of the list. It's usually called as an infix function because it's easier to read that way.
|
||||
|
||||
Function for infinite lists:
|
||||
|
||||
cycle: takes a list and cycles it into an infinite list. If you just try to display the result, it will go on forever so you have to slice it off somewhere.
|
||||
repeat: takes an element and produces an infinite list of just that element. It's like cycling a list with only one element.
|
||||
replicate: takes the number of the same element in a list.
|
||||
|
||||
List comprehension
|
||||
|
||||
List comprehension is the process of generating a list using a mathematical expression.
|
||||
|
||||
[body | generator]
|
||||
|
||||
Examples: [x*a | a <- [1..3]] = [2,4,6]
|
||||
[x*y | x <- [1..5], y <- [9..5] ]
|
||||
[x | x <- [1,10,14,16,18], x>5 ]
|
||||
|
||||
Tuples
|
||||
|
||||
(1,"a") - 2-element tuple of a number and a string
|
||||
(last, 4, 'b') - 3-element tuple of a function, a number and a character
|
||||
|
||||
Note that the empty tuple () is also a type which can only have a single value: ()
|
||||
|
||||
Basic functions for Tuples
|
||||
|
||||
fst: takes a pair and returns its first component.
|
||||
snd: takes a pair and returns its second component.
|
||||
zip: takes two lists and then zips them together into one list by joining the matching elements into pairs.
|
||||
|
||||
Note: these functions operate only on pairs. They won't work on triples, 4-tuples, 5-tuples, etc.
|
||||
|
||||
|
||||
Typeclasses
|
||||
|
||||
A typeclass is a sort of interface that defines some behaviour.
|
||||
If a type is a part of a typeclass, that means that it supports and implements the behavior the typeclass describes.
|
||||
If you come from OPP you can think of them kind of as Java interfaces, only better.
|
||||
|
||||
Everything before the => symbol is called a class constraint.
|
||||
|
||||
Eq is used for types that support equality testing. Eq class constraint for a type variable in a function, it uses == or /= somewhere inside its definition
|
||||
Ord is for types that have an ordering. Ord covers all the standard comparing functions such as >, <, >= and <=
|
||||
Show can be presented as strings. show takes a value whose type is a member of Show and presents it to us as a string.
|
||||
Read is sort of the opposite typeclass of Show. The read function takes a string and returns a type which is a member of Read.
|
||||
Enum members are sequentially ordered types, they can be enumerated. Types in this class: (), Bool, Char, Ordering, Int, Integer, Float and Double.
|
||||
Bounded members have an upper and a lower bound. All tuples are part of Bounded. Types in this class: Bool, Int and Char.
|
||||
Num is a numeric typeclass. Types in this class: Int, Integer, Float and Double.
|
||||
Integral is also a numeric typeclass. In this typeclass are Int and Integer.
|
||||
Floating includes only floating point numbers. Types in this class: Float and Double.
|
||||
|
||||
Functions
|
||||
|
||||
Functions are defined by declaring their name, any arguments, and an equals sign.
|
||||
|
||||
Declare a new function starting with explicit type declaration (optional)
|
||||
functionName :: inpuntType1 [ -> inputTypeN ] -> outputType
|
||||
|
||||
Declare a new function with pattern matching
|
||||
intToChar 1 = "One"
|
||||
intToChar 2 = "Two"
|
||||
|
||||
Declare a new function with guards
|
||||
intToChar x
|
||||
| x==1 = "One"
|
||||
| x==2 = "Two"
|
||||
|
||||
Declare a new function with guards and pattern matching
|
||||
allEmpty _ = falsePart
|
||||
allEmpty [] = truePart
|
||||
|
||||
alwaysEven n
|
||||
| otherwise = False
|
||||
| n 'div' 2 == 0 = True
|
||||
|
||||
Declare a new function with record syntax
|
||||
|
||||
Being this data type:
|
||||
data Color = C { red,
|
||||
, blue
|
||||
, yellow :: Int }
|
||||
|
||||
It can only be match on blue only:
|
||||
|
||||
isBlueZero (C { blue = 0 }) = True
|
||||
isBlueZero _ = False
|
||||
|
||||
Defining a PixelColor type and a function replace values with non-zero blue components.
|
||||
|
||||
Where and let
|
||||
|
||||
Let must always be followed by in. The in must appear in the sale column as the let keyword.
|
||||
In the following example, mult multiples its argument n by x, which passed to the original multiples.
|
||||
multiples x =
|
||||
let mult n = n * x
|
||||
in map mult [1..10]
|
||||
|
||||
|
||||
Where is similar to let. The scope of a where definition is the current function.
|
||||
In the following example, the function result below has a different meaning depending on the arguments given to the function strlen:
|
||||
strlen [] = result
|
||||
where result = "No string given!"
|
||||
strlen f = result ++ " characters long!"
|
||||
where result = show (length f)
|
||||
|
||||
|
||||
It is important to know that let ... in ... is an expression, that is, it can be written wherever expressions are allowed.
|
||||
In contrast, where is bound to a surrounding syntactic construct, like the pattern matching line of a function definition.
|
||||
|
||||
Advantage of where
|
||||
Suppose you have the function
|
||||
f :: s -> (a,s)
|
||||
f x = y
|
||||
where y = ... x ...
|
||||
and later you decide to put this into the Control.Monad.State monad.
|
||||
|
||||
However, transforming to
|
||||
f :: State s a
|
||||
f = State $ \x -> y
|
||||
where y = ... x ...
|
||||
will not work, because where refers to the pattern matching f =, where no x is in scope. In contrast, if you had started with let, then you wouldn't have trouble.
|
||||
f :: s -> (a,s)
|
||||
f x =
|
||||
let y = ... x ...
|
||||
in y
|
||||
|
||||
This is easily transformed to:
|
||||
f :: State s a
|
||||
f = State $ \x ->
|
||||
let y = ... x ...
|
||||
in y
|
||||
|
||||
Advantage of let
|
||||
|
||||
Because "where" blocks are bound to a syntactic construct, they can be used to share bindings between parts of a function that are not syntactically expressions.
|
||||
For example:
|
||||
f x
|
||||
| cond1 x = a
|
||||
| cond2 x = g a
|
||||
| otherwise = f (h x a)
|
||||
where
|
||||
a = w x
|
||||
|
||||
In expression style, you might use an explicit case:
|
||||
f x
|
||||
= let a = w x
|
||||
in case () of
|
||||
_ | cond1 x -> a
|
||||
| cond2 x -> g a
|
||||
| otherwise -> f (h x a)
|
||||
|
||||
or a functional equivalent:
|
||||
f x =
|
||||
let a = w x
|
||||
in select (f (h x a))
|
||||
[(cond1 x, a),
|
||||
(cond2 x, g a)]
|
||||
or a series of if-then-else expressions:
|
||||
f x
|
||||
= let a = w x
|
||||
in if cond1 x
|
||||
then a
|
||||
else if cond2 x
|
||||
then g a
|
||||
|
||||
|
||||
Anonymous Functions
|
||||
|
||||
They are functions without names and can be defined at any time like so.
|
||||
Example: \x -> x + 1
|
||||
|
||||
Case expressions
|
||||
|
||||
case is to a switch statement in C# and Java. However, it can match a pattern.
|
||||
Example:
|
||||
data Choices = First String | Second | Third | Fourth
|
||||
|
||||
case can be used to determine which choice was given
|
||||
|
||||
whichChoice ch =
|
||||
case ch of
|
||||
First _ -> "1st!"
|
||||
Second -> "2nd!"
|
||||
_ -> "Something else."
|
||||
|
||||
|
||||
Conditionals
|
||||
|
||||
Identify ==
|
||||
Non identify /n
|
||||
Comparatives where the type must a subclass of Ord <,>,<=,>=
|
||||
|
||||
The if statement has this “signature”: if-then-else :: Bool -> a -> a -> a
|
||||
|
||||
Maps and filters
|
||||
|
||||
map takes a function and a list and applies that function to every element in the list, producing a new list.
|
||||
Examples:
|
||||
map :: (a -> b) -> [a] -> [b]
|
||||
map _ [] = []
|
||||
map f (x:xs) = f x : map f xs
|
||||
|
||||
filter is a function that takes a predicate and nd a list and then returns the list of elements that satisfy the predicate
|
||||
Examples:
|
||||
filter :: (a -> Bool) -> [a] -> [a]
|
||||
filter _ [] = []
|
||||
filter p (x:xs)
|
||||
| p x = x : filter p xs
|
||||
| otherwise = filter p xs
|
||||
|
||||
Folds
|
||||
|
||||
foldl function folds the list up from the left side.
|
||||
foldr works in a similar way to the left fold, only the accumulator eats up the values from the right.
|
||||
|
||||
The foldl1 and foldr1 functions work much like foldl and foldr, only you don't need to provide them with an explicit starting value.
|
||||
|
||||
scanl and scanr are like foldl and foldr, only they report all the intermediate accumulator states in the form of a list.
|
||||
|
||||
Function application with $
|
||||
|
||||
The $ function has the lowest precedence and the function with $ is rigth-associate
|
||||
|
||||
Default
|
||||
|
||||
Default implementations can be given for function in a class.
|
||||
|
||||
The default is defined by giving a body to one of the members' functions.
|
||||
Example == can be defined in terms of /=:
|
||||
(==) a b = not (a/b)
|
||||
|
||||
Data
|
||||
|
||||
Algebraic data types can be declared as: data MyType = MyValue1 | MyValue2
|
||||
|
||||
Note that type and constructor names must start with a capital letter. It is a syntax error otherwise.
|
||||
|
||||
|
||||
Constructors with arguments
|
||||
|
||||
Constructors that take arguments can be declared, allowing more information to be stored.
|
||||
|
||||
data Point = TwoD Int Int
|
||||
| ThreeD Int Int Int
|
||||
|
||||
Notice that the arguments for each constructor are type names, not constructors.
|
||||
|
||||
Type and constructor names
|
||||
|
||||
Both names can be the same since they will never be used in a place that would cause confusion.
|
||||
data User = User String | Admin String
|
||||
|
||||
Using this type in a function makes difference clear:
|
||||
whatUser (User _) = "normal user"
|
||||
whatUser (Admin _) = "admin user"
|
||||
|
||||
Type Variables
|
||||
|
||||
Plymorphic data types are easy to be declared just by adding type varialbe in the declaration:
|
||||
data Slot a = Slot1 a | Empty1
|
||||
|
||||
It can also be mix type variable and specific types in constructors:
|
||||
data Slot2 a = Slot2 a Int | Empty2
|
||||
|
||||
Record syntax
|
||||
|
||||
Constructors arguments can also be declared by using record syntax which gives a name to each argument.
|
||||
For example:
|
||||
data Contact = Contact { ctName :: String
|
||||
, ctEmail :: String
|
||||
, ctPhone :: String }
|
||||
|
||||
Note: Multiple constructors of the same type can use the same accessor function name for values of the same type.
|
||||
|
||||
Deriving
|
||||
|
||||
The capabilities to convert to and from strings, compare
|
||||
for equality, or order in a sequence are defined as Typeclasses and Haskell provides the deriving keyboard to automatically implement the typeclass on the associated type supported which are: Eq, Read, Show, Ord, Enum, Ix, and
|
||||
Bounded.
|
||||
|
||||
Two forms of deriving are possible.
|
||||
|
||||
The first is used when a type only derives one class:
|
||||
data Priority = Low | Medium | High
|
||||
deriving Show
|
||||
|
||||
The second is used when multiple classes are derived:
|
||||
data Alarm = Soft | Loud | Deafening
|
||||
deriving (Read, Show)
|
||||
|
||||
Class constraint
|
||||
|
||||
In any case, the syntax used is:
|
||||
data (Num a) => SomeNumber a = Two a a
|
||||
| Three a a a
|
||||
|
||||
This declares a type SomeNumber which has one type variable argument.
|
||||
Valid types are those in the Num class.
|
||||
|
||||
Do
|
||||
|
||||
Do indicates that the code to follow will be in a monadic context.
|
||||
Statements are separated by newlines, the assignment is indicated by <, and a let form is introduced which does not require the in the keyboard.
|
||||
|
||||
If, Then, Else
|
||||
|
||||
This function tests if the string is given starts with a lower case letter and, if so, convert it to upper case:
|
||||
|
||||
sentenceCase (s:rest) =
|
||||
if isLower s
|
||||
then toUpper s : rest
|
||||
else s : result
|
||||
sentenceCase _ = []
|
||||
|
||||
Deconstruction
|
||||
|
||||
The left-hand side of a let definition can also destructive its argument, in case sub-components are to be accessed.
|
||||
Examples:
|
||||
firstThree str =
|
||||
let (a:b:c:_) = str
|
||||
in "Initial three characters are: " ++
|
||||
show a ++ ", " ++
|
||||
show b ++ ", and " ++
|
||||
show c
|
||||
|
||||
Note that this is different than the following, which only works if the string has exactly three characters:
|
||||
onlyThree str =
|
||||
let (a:b:c:[]) = str
|
||||
in "The characters given are: " ++
|
||||
show a ++ ", " ++
|
||||
show b ++ ", and " ++
|
||||
show c
|
||||
|
||||
Modules
|
||||
|
||||
A module is a compilation unit which export functions, tyñes, classes, instances, and other modules.
|
||||
To make a Haskell file a module just add at the top of it:
|
||||
module MyModule where
|
||||
|
||||
Imports
|
||||
|
||||
To import everything (functions, data types and constructors, class declarations, and even other modules imported) exported by a library, just use the module name:
|
||||
import Text.Read
|
||||
|
||||
To import selectively:
|
||||
import Text.Read (readParen, lex)
|
||||
|
||||
To import data types and no constructors:
|
||||
import Text.Read (Lexeme)
|
||||
|
||||
To import data types and one or more constructors explicitly
|
||||
import Text.Read (Lexeme(Ident, Symbol))
|
||||
|
||||
To import all constructors for a given type:
|
||||
import Text.Read (Lexeme())
|
||||
@@ -0,0 +1,344 @@
|
||||
Java Cheatsheet
|
||||
|
||||
HELLO WORLD
|
||||
|
||||
//Text file name HelloWorld.java
|
||||
public class HelloWorld {
|
||||
// main() is the method
|
||||
public static void main (String[] arfs)
|
||||
//Prints "Hello World" in the terminal window.
|
||||
System.out.pritn("Hello World");
|
||||
}
|
||||
|
||||
DATA TYPES
|
||||
|
||||
Type Set of values Values Operators
|
||||
int integers between -2^31 and + (2^31)-1 + - * / %
|
||||
double floating-point numbers real numbers + - * /
|
||||
boolean boolean values true or false && || !
|
||||
char characters
|
||||
String sequences of characters
|
||||
|
||||
DECLARATION AND ASSIGNMENT STATEMENTS
|
||||
|
||||
//Declaration statement
|
||||
int a,b;
|
||||
|
||||
//Assignment statement
|
||||
a = 13212; //a is the variable name; 13212 is the literal which is assign to the variable a
|
||||
|
||||
//Initialization statement
|
||||
int c = a + b;
|
||||
|
||||
COMPARISON OPERATORS
|
||||
|
||||
Operation Meaning
|
||||
== equal
|
||||
!= not equal
|
||||
< less than
|
||||
> greater than
|
||||
<= less than or equal
|
||||
>= greater than or equal
|
||||
|
||||
|
||||
PRINTING
|
||||
|
||||
void System.out.print(String s) //print s
|
||||
void System.out.println(String s) //print s, followed by a newline
|
||||
void System.out.println() //print a newline
|
||||
|
||||
PARSING COMMAND-LINE ARGUMENTS
|
||||
|
||||
int Integer.parseInt(String s) //convert s to an int value
|
||||
double Double.parseDouble(String) //convert s to a double value
|
||||
long Long.parseLong(String s) // convert s to a long value
|
||||
|
||||
MATH LIBRARY
|
||||
|
||||
Public Class Math
|
||||
double abs(double a) // absolute value of a
|
||||
double max(double a, double b) //maximum of a and b
|
||||
double min(double a, dobule a) //minimum of a and b
|
||||
double sin(double theta) //sine of theta
|
||||
double cos(double theta) //cosine of theta
|
||||
double tan(double theta) //tangent of theta
|
||||
double toRadians(double degrees) // convert angle from degrees to radians
|
||||
double toDegreestouble radians) // convert angle from radians to degrees
|
||||
double exp(doube a) // exponential (e^a)
|
||||
double pow(double a, double p) //raise a to the bth power (a^b)
|
||||
double random() //random in [0,1)
|
||||
double sqrt(double a) //square root of a
|
||||
|
||||
|
||||
EXAMPLES OF TYPE CONVERSION
|
||||
|
||||
Expression Expression type Expression value
|
||||
(1 + 2 + 3 + 4) / 4.0 double 2.5
|
||||
Math.sqrt(4) double 2.0
|
||||
"123343" + 99 String "12334399"
|
||||
11 * 0.25 double 2.75
|
||||
(int) 11 * 0.25 double 2.75
|
||||
11 * (int) 0.25 int 0
|
||||
(int) (11 * 0.25) int 2
|
||||
|
||||
|
||||
ANATOMY OF AN IF STATEMENT
|
||||
|
||||
if (x>y) { // x > y is the boolean expression
|
||||
//Sequence of statements
|
||||
x = y;
|
||||
}
|
||||
|
||||
IF AND IF-ELSE STATEMENT
|
||||
|
||||
if (BOOLEAN EXPRESSION) {
|
||||
//Sequence of statements
|
||||
} else {
|
||||
//Sequence of statements
|
||||
}
|
||||
|
||||
ANATOMY OF A WHILE LOOP
|
||||
|
||||
//Initialization is a separate statement
|
||||
int power = 1;
|
||||
|
||||
while ( power <= n/2 ) // power <= n/2 is an example of the loop-continuation condition
|
||||
{
|
||||
//Statements
|
||||
}
|
||||
|
||||
ANATOMY OF A WHILE LOOP
|
||||
|
||||
//Initialize another variable in a separate statement
|
||||
int power = 1;
|
||||
|
||||
for (declare and initialize a loop control variable; loop-continuation condition/s; increment or decrement of the variable of control)
|
||||
{
|
||||
//Statement
|
||||
}
|
||||
|
||||
Example:
|
||||
for (int i = 0; i <= n; i++) {
|
||||
//Statement
|
||||
}
|
||||
|
||||
DO-WHILE LOOP
|
||||
|
||||
do{
|
||||
//Statement
|
||||
} while(lopp-continuation condition);
|
||||
|
||||
SWITCH STATEMENT
|
||||
|
||||
switch (VARIABLE TO EVALUATE ITS VALUE) {
|
||||
case value: Statement; break;
|
||||
...
|
||||
default: Statement; break;
|
||||
}
|
||||
|
||||
Example:
|
||||
|
||||
int month = 8;
|
||||
String monthString;
|
||||
switch (month) {
|
||||
case 1: monthString = "January";
|
||||
break;
|
||||
case 2: monthString = "February";
|
||||
break;
|
||||
case 3: monthString = "March";
|
||||
break;
|
||||
case 4: monthString = "April";
|
||||
break;
|
||||
case 5: monthString = "May";
|
||||
break;
|
||||
case 6: monthString = "June";
|
||||
break;
|
||||
case 7: monthString = "July";
|
||||
break;
|
||||
case 8: monthString = "August";
|
||||
break;
|
||||
case 9: monthString = "September";
|
||||
break;
|
||||
case 10: monthString = "October";
|
||||
break;
|
||||
case 11: monthString = "November";
|
||||
break;
|
||||
case 12: monthString = "December";
|
||||
break;
|
||||
default: monthString = "Invalid month";
|
||||
break;
|
||||
}
|
||||
|
||||
ARRAY DECLARATION
|
||||
|
||||
int[] ai; // array of int
|
||||
short[][] as; // array of array of short
|
||||
short s, // scalar short
|
||||
aas[][]; // array of array of short
|
||||
Object[] ao, // array of Object
|
||||
otherAo; // array of Object
|
||||
Collection<?>[] ca; // array of Collection of unknown type
|
||||
|
||||
DECLARATION OF ARRAY VARIABLE
|
||||
|
||||
Exception ae[] = new Exception[3];
|
||||
Object aao[][] = new Exception[2][3];
|
||||
int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
|
||||
char ac[] = { 'n', 'o', 't', ' ', 'a', ' ',
|
||||
'S', 't', 'r', 'i', 'n', 'g' };
|
||||
String[] aas = { "array", "of", "String", };
|
||||
|
||||
FUNCTIONS
|
||||
|
||||
public static double sum (int a, int b) { //double is the return type, sum is the method's name, a and b are two arguments of type int;
|
||||
int result; //local variable
|
||||
result = a + b;
|
||||
return result;//return statement;
|
||||
}
|
||||
|
||||
USING AN OBJECT
|
||||
|
||||
//Declare a a variable, object name
|
||||
String s;
|
||||
|
||||
//Invoke a contructor to create an object
|
||||
s = new String ("Hello World");
|
||||
|
||||
//Invoke an instance method that operates on the object's value
|
||||
char c = s.chartAt(4);
|
||||
|
||||
INSTANCE VARIABLES
|
||||
|
||||
public class Charge {
|
||||
//Instance variable declarations
|
||||
private final double rx, ry;
|
||||
private final double q;
|
||||
}
|
||||
|
||||
//private, final and public are access modifiers
|
||||
|
||||
|
||||
CONSTRUCTORS
|
||||
|
||||
//A class contains constructors that are invoked to create objects from the class blueprint.
|
||||
//Constructor declarations look like method declarations—except that they use the name of the class and have no return type
|
||||
|
||||
public Bicycle(int startCadence, int startSpeed, int startGear) {
|
||||
gear = startGear;
|
||||
cadence = startCadence;
|
||||
speed = startSpeed;
|
||||
}
|
||||
|
||||
DECLARING CLASSESS
|
||||
|
||||
|
||||
class MyClass {
|
||||
// field, constructor, and
|
||||
// method declarations
|
||||
}
|
||||
|
||||
Example:
|
||||
|
||||
public class Bicycle {
|
||||
// the Bicycle class has
|
||||
// three fields
|
||||
public int cadence;
|
||||
public int gear;
|
||||
public int speed;
|
||||
// the Bicycle class has
|
||||
// one constructor
|
||||
public Bicycle(int startCadence, int startSpeed, int startGear) {
|
||||
gear = startGear;
|
||||
cadence = startCadence;
|
||||
speed = startSpeed;
|
||||
}
|
||||
// the Bicycle class has
|
||||
// four methods
|
||||
public void setCadence(int newValue) {
|
||||
cadence = newValue;
|
||||
}
|
||||
public void setGear(int newValue) {
|
||||
gear = newValue;
|
||||
}
|
||||
public void applyBrake(int decrement) {
|
||||
speed -= decrement;
|
||||
}
|
||||
public void speedUp(int increment) {
|
||||
speed += increment;
|
||||
}
|
||||
|
||||
DECLARING CLASSESS IMPLEMENTATING AN INTERFACE
|
||||
|
||||
class MyClass extends MySuperClass implements YourInterface {
|
||||
// field, constructor, and
|
||||
// method declarations
|
||||
}
|
||||
|
||||
// MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.
|
||||
|
||||
|
||||
STACK DATA TYPE
|
||||
|
||||
public class Stack<Item> implements Iterable <Item>
|
||||
|
||||
Stack() //create an empty stack
|
||||
boolean isEmpthy() //return if the stack empthy
|
||||
void push(Item item) // push an item onto the stack
|
||||
Item pop() //return and remove the item that was inserted most recently
|
||||
int size() //number of item on stack
|
||||
|
||||
QUEUE DATA TYPE
|
||||
|
||||
public class Queue<Item> implements Iterable<Item>
|
||||
|
||||
Queue() //create an emptyh queue
|
||||
boolean isEmpthy() //return if the queue empthy
|
||||
void enqueue(Item item) // insert an item onto queue
|
||||
Item dequeue() //return and remove the item that was inserted least recently
|
||||
int size() //number of item on queue
|
||||
|
||||
ITERABLE
|
||||
|
||||
//import Iterator
|
||||
import java.util.Iterator;
|
||||
|
||||
public class Queue<Item> implements Iterable <Item> {
|
||||
|
||||
//FIFO queue
|
||||
private Node first;
|
||||
private Node last;
|
||||
private class Node {
|
||||
Item item;
|
||||
Node next;
|
||||
}
|
||||
|
||||
public void enqueue (Item item)
|
||||
...
|
||||
|
||||
public Item dequeue()
|
||||
...
|
||||
|
||||
}
|
||||
|
||||
SYMBOL TABLE DATA TYPE
|
||||
|
||||
public class ST<Key extends Comparable<Key>, Value>
|
||||
|
||||
ST() //create and empthy symbol table
|
||||
void put(Key key, Value val) //associate val with key
|
||||
Value get(Key key) //value associated with key
|
||||
void remove(Key key) //remove key (and its associated value)
|
||||
boolean contains (Key key) //return if there is a value associated with key
|
||||
int size() //number of key-value pairs
|
||||
Iterable<Key> keys() // all keys in the symbol table
|
||||
|
||||
SET DATA TYPE
|
||||
|
||||
public class SET<Key extends Comparable<Key>> implements Iterable<Key>
|
||||
SET() //create an empthy set
|
||||
boolean isEmpthy() //return if the set is empthy
|
||||
void add (Key key) //add key to the set
|
||||
void remove(Key key) //remove key from set
|
||||
boolean contains(Key key) //return if the key is in the set
|
||||
int size() //number of elements in set
|
||||
|
||||
@@ -95,9 +95,3 @@ arr.reduce(callback[, initialValue]) // Apply a function against
|
||||
arr.reduceRight(callback[, initialValue]) // Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.
|
||||
arr.some(callback[, initialValue]) // Returns true if at least one element in this array satisfies the provided testing function.
|
||||
arr.values() // Returns a new Array Iterator object that contains the values for each index in the array.
|
||||
|
||||
// String methods
|
||||
String.charAt(index) // Returns the character at the specified index in a string.
|
||||
String.indexOf(character) // Returns the index of the first occurrence of a specified value in a string.
|
||||
String.substring(starting_index, ending_index) // Returns a new string that is a subset of the original string.
|
||||
String.substring(starting_index) // Returns a substring from starting index to last index of string.
|
||||
@@ -1,815 +0,0 @@
|
||||
# TypeScript
|
||||
|
||||
* TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript
|
||||
|
||||
* It adds optional static type definitions to JavaScript, enabling better tooling and error detection
|
||||
|
||||
* In TypeScript, types are checked at compile-time, not runtime
|
||||
|
||||
* A TypeScript file has an extension of .ts (or .tsx for React components)
|
||||
|
||||
* TypeScript follows JavaScript syntax but adds type annotations and advanced features
|
||||
|
||||
* We can compile and run a TypeScript file by the following commands:
|
||||
|
||||
`$ tsc filename.ts` (compile to JavaScript)
|
||||
`$ node filename.js` (run the compiled JavaScript)
|
||||
|
||||
Or directly: `$ ts-node filename.ts`
|
||||
|
||||
#### TypeScript requires compilation to JavaScript before execution.
|
||||
|
||||
## Create and execute a program
|
||||
|
||||
1. Install TypeScript globally: `npm install -g typescript`
|
||||
1. Create the program: `touch program.ts`
|
||||
1. Write the TypeScript code and save it
|
||||
1. Compile: `tsc program.ts`
|
||||
1. Run: `node program.js`
|
||||
|
||||
<br>
|
||||
|
||||
### Basic Data Types
|
||||
|
||||
| Data Type | Description | Example |
|
||||
| --------- | ----------- | ------- |
|
||||
| number | Integer and floating point values | `42`, `3.14`, `-7` |
|
||||
| string | Text values | `"hello"`, `'world'`, `` `template` `` |
|
||||
| boolean | True/false values | `true`, `false` |
|
||||
| undefined | Undefined value | `undefined` |
|
||||
| null | Null value | `null` |
|
||||
| any | Any type (disables type checking) | Can be anything |
|
||||
| unknown | Type-safe counterpart of any | Requires type checking |
|
||||
| void | Absence of any type | Function return type |
|
||||
| never | Type that never occurs | Functions that throw errors |
|
||||
| object | Non-primitive types | `{}`, `[]`, functions |
|
||||
|
||||
<br>
|
||||
|
||||
## Keywords and Reserved Words
|
||||
<br>
|
||||
|
||||
- TypeScript includes all JavaScript keywords plus additional TypeScript-specific ones
|
||||
|
||||
| Keyword | Description | Category |
|
||||
|---------- | ---------- | --------- |
|
||||
| let | Declares a block-scoped variable | Variable Declaration |
|
||||
| const | Declares a block-scoped constant | Variable Declaration |
|
||||
| var | Declares a function-scoped variable | Variable Declaration |
|
||||
| function | Declares a function | Function |
|
||||
| class | Declares a class | Class |
|
||||
| interface | Declares an interface | Type Definition |
|
||||
| type | Declares a type alias | Type Definition |
|
||||
| enum | Declares an enumeration | Type Definition |
|
||||
| namespace | Declares a namespace | Module System |
|
||||
| module | Declares a module | Module System |
|
||||
| import | Imports from another module | Module System |
|
||||
| export | Exports from current module | Module System |
|
||||
| extends | Class/interface inheritance | Inheritance |
|
||||
| implements | Class implements interface | Inheritance |
|
||||
| public | Public access modifier | Access Modifier |
|
||||
| private | Private access modifier | Access Modifier |
|
||||
| protected | Protected access modifier | Access Modifier |
|
||||
| readonly | Read-only property | Access Modifier |
|
||||
| static | Static class member | Class Member |
|
||||
| abstract | Abstract class/method | Class |
|
||||
| async | Asynchronous function | Async Programming |
|
||||
| await | Awaits a promise | Async Programming |
|
||||
| new | Creates new instance | Object Creation |
|
||||
| this | Current object reference | Object Reference |
|
||||
| super | Parent class reference | Inheritance |
|
||||
| typeof | Gets type of variable | Type Operation |
|
||||
| keyof | Gets keys of type | Type Operation |
|
||||
| in | Property existence check | Type Guard |
|
||||
| instanceof | Instance type check | Type Guard |
|
||||
| as | Type assertion | Type Assertion |
|
||||
| is | Type predicate | Type Guard |
|
||||
| infer | Infers type in conditional types | Advanced Types |
|
||||
| declare | Ambient declarations | Declaration |
|
||||
| get | Property getter | Accessor |
|
||||
| set | Property setter | Accessor |
|
||||
| yield | Generator yield | Generator |
|
||||
|
||||
<br>
|
||||
|
||||
## Operators
|
||||
|
||||
<br>
|
||||
|
||||
| Operator | Description |
|
||||
|-|-|
|
||||
| ( ) | Grouping, function call, type assertion |
|
||||
| [ ] | Array indexing, array/tuple types |
|
||||
| . | Property access |
|
||||
| ?. | Optional chaining |
|
||||
| ! | Non-null assertion, logical not |
|
||||
| ~ | Bitwise not |
|
||||
| \- | Unary minus, arithmetic subtraction |
|
||||
| \+ | Unary plus, arithmetic addition |
|
||||
| \* | Multiplication |
|
||||
| / | Division |
|
||||
| % | Modulo |
|
||||
| \*\* | Exponentiation |
|
||||
| << | Left shift |
|
||||
| \>> | Right shift |
|
||||
| \>>> | Unsigned right shift |
|
||||
| < | Less than |
|
||||
| <= | Less than or equal |
|
||||
| \> | Greater than |
|
||||
| \>= | Greater than or equal |
|
||||
| == | Equality (with coercion) |
|
||||
| === | Strict equality |
|
||||
| != | Inequality (with coercion) |
|
||||
| !== | Strict inequality |
|
||||
| & | Bitwise AND |
|
||||
| ^ | Bitwise XOR |
|
||||
| \| | Bitwise OR, Union types |
|
||||
| && | Logical AND |
|
||||
| \|\| | Logical OR |
|
||||
| ?? | Nullish coalescing |
|
||||
| ? : | Ternary conditional |
|
||||
| = | Assignment |
|
||||
| += | Add and assign |
|
||||
| -= | Subtract and assign |
|
||||
| *= | Multiply and assign |
|
||||
| /= | Divide and assign |
|
||||
| %= | Modulo and assign |
|
||||
| **= | Exponentiate and assign |
|
||||
| <<= | Left shift and assign |
|
||||
| \>>= | Right shift and assign |
|
||||
| &= | Bitwise AND and assign |
|
||||
| ^= | Bitwise XOR and assign |
|
||||
| \|= | Bitwise OR and assign |
|
||||
| , | Comma operator |
|
||||
| => | Arrow function |
|
||||
| ... | Spread/rest operator |
|
||||
|
||||
### Basic Data Structures
|
||||
|
||||
### Array
|
||||
|
||||
- Array is an ordered collection of elements of the same or different types.
|
||||
|
||||
- Arrays are created using square brackets or Array constructor:
|
||||
|
||||
```typescript
|
||||
let numbers: number[] = [1, 2, 3, 4];
|
||||
let fruits: Array<string> = ["apple", "banana", "cherry"];
|
||||
let mixed: (string | number)[] = [1, "two", 3];
|
||||
```
|
||||
|
||||
- Array elements are indexed starting from 0.
|
||||
|
||||
- Arrays are mutable - you can change, add, and remove elements.
|
||||
|
||||
- Common array methods:
|
||||
```typescript
|
||||
let arr = [1, 2, 3];
|
||||
arr.push(4); // Add to end: [1, 2, 3, 4]
|
||||
arr.pop(); // Remove from end: [1, 2, 3]
|
||||
arr.unshift(0); // Add to start: [0, 1, 2, 3]
|
||||
arr.shift(); // Remove from start: [1, 2, 3]
|
||||
arr.length; // Get length: 3
|
||||
```
|
||||
|
||||
### Tuple
|
||||
|
||||
- Tuple is an array with a fixed number of elements of specific types.
|
||||
|
||||
- Tuples are created using square brackets with type annotations:
|
||||
```typescript
|
||||
let person: [string, number] = ["John", 30];
|
||||
let coordinate: [number, number] = [10, 20];
|
||||
```
|
||||
|
||||
- Tuple elements are ordered and have specific types at each position.
|
||||
|
||||
- You can access elements by index, but type checking ensures correctness:
|
||||
```typescript
|
||||
let point: [number, number] = [10, 20];
|
||||
console.log(point[0]); // 10 (number)
|
||||
console.log(point[1]); // 20 (number)
|
||||
```
|
||||
|
||||
- Named tuples provide better readability:
|
||||
```typescript
|
||||
let user: [name: string, age: number] = ["Alice", 25];
|
||||
```
|
||||
|
||||
- Optional and rest elements in tuples:
|
||||
```typescript
|
||||
let optional: [string, number?] = ["hello"];
|
||||
let rest: [string, ...number[]] = ["coords", 1, 2, 3];
|
||||
```
|
||||
|
||||
### Set
|
||||
|
||||
- Set is a collection of unique values of any type.
|
||||
|
||||
- Sets are created using the Set constructor:
|
||||
```typescript
|
||||
let uniqueNumbers = new Set<number>([1, 2, 3, 2]); // {1, 2, 3}
|
||||
let stringSet = new Set<string>();
|
||||
```
|
||||
|
||||
- Set operations:
|
||||
```typescript
|
||||
let mySet = new Set<string>();
|
||||
mySet.add("apple"); // Add element
|
||||
mySet.has("apple"); // Check existence: true
|
||||
mySet.delete("apple"); // Remove element
|
||||
mySet.clear(); // Remove all elements
|
||||
mySet.size; // Get size
|
||||
```
|
||||
|
||||
- Iterating over Set:
|
||||
```typescript
|
||||
let fruits = new Set(["apple", "banana", "cherry"]);
|
||||
for (let fruit of fruits) {
|
||||
console.log(fruit);
|
||||
}
|
||||
```
|
||||
|
||||
### Map
|
||||
|
||||
- Map is a collection of key-value pairs where keys can be any type.
|
||||
|
||||
- Maps are created using the Map constructor:
|
||||
```typescript
|
||||
let userMap = new Map<string, number>();
|
||||
let mixedMap = new Map<string | number, any>();
|
||||
```
|
||||
|
||||
- Map operations:
|
||||
```typescript
|
||||
let map = new Map<string, number>();
|
||||
map.set("age", 30); // Add key-value pair
|
||||
map.get("age"); // Get value: 30
|
||||
map.has("age"); // Check key exists: true
|
||||
map.delete("age"); // Remove key-value pair
|
||||
map.clear(); // Remove all entries
|
||||
map.size; // Get size
|
||||
```
|
||||
|
||||
- Object vs Map:
|
||||
```typescript
|
||||
// Object - string/symbol keys only
|
||||
let obj: { [key: string]: number } = { "age": 30 };
|
||||
|
||||
// Map - any type keys
|
||||
let map = new Map<any, number>();
|
||||
map.set("age", 30);
|
||||
map.set(42, 100);
|
||||
map.set(true, 1);
|
||||
```
|
||||
|
||||
### Object Types and Interfaces
|
||||
|
||||
- Objects store key-value pairs and are fundamental to TypeScript.
|
||||
|
||||
- Object type annotation:
|
||||
```typescript
|
||||
let person: { name: string; age: number } = {
|
||||
name: "John",
|
||||
age: 30
|
||||
};
|
||||
```
|
||||
|
||||
- Interface definition for better reusability:
|
||||
```typescript
|
||||
interface User {
|
||||
readonly id: number; // Read-only property
|
||||
name: string;
|
||||
age?: number; // Optional property
|
||||
[key: string]: any; // Index signature
|
||||
}
|
||||
|
||||
let user: User = {
|
||||
id: 1,
|
||||
name: "Alice"
|
||||
};
|
||||
```
|
||||
|
||||
- Nested objects and complex types:
|
||||
```typescript
|
||||
interface Address {
|
||||
street: string;
|
||||
city: string;
|
||||
country: string;
|
||||
}
|
||||
|
||||
interface Person {
|
||||
name: string;
|
||||
address: Address;
|
||||
hobbies: string[];
|
||||
}
|
||||
```
|
||||
|
||||
### Conditional branching
|
||||
|
||||
```typescript
|
||||
// If-else statements
|
||||
if (condition) {
|
||||
// code block
|
||||
} else if (anotherCondition) {
|
||||
// code block
|
||||
} else {
|
||||
// code block
|
||||
}
|
||||
|
||||
// Ternary operator
|
||||
let result = condition ? valueIfTrue : valueIfFalse;
|
||||
|
||||
// Switch statement
|
||||
switch (variable) {
|
||||
case value1:
|
||||
// code
|
||||
break;
|
||||
case value2:
|
||||
// code
|
||||
break;
|
||||
default:
|
||||
// code
|
||||
break;
|
||||
}
|
||||
```
|
||||
|
||||
### Loops
|
||||
|
||||
TypeScript supports all JavaScript loop constructs:
|
||||
|
||||
#### For loop
|
||||
```typescript
|
||||
// Traditional for loop
|
||||
for (let i = 0; i < 5; i++) {
|
||||
console.log(i);
|
||||
}
|
||||
|
||||
// For-of loop (iterates over values)
|
||||
let fruits = ["apple", "banana", "cherry"];
|
||||
for (let fruit of fruits) {
|
||||
console.log(fruit);
|
||||
}
|
||||
|
||||
// For-in loop (iterates over keys/indices)
|
||||
for (let index in fruits) {
|
||||
console.log(index, fruits[index]);
|
||||
}
|
||||
```
|
||||
|
||||
#### While loop
|
||||
```typescript
|
||||
let i = 0;
|
||||
while (i < 5) {
|
||||
console.log(i);
|
||||
i++;
|
||||
}
|
||||
|
||||
// Do-while loop
|
||||
let j = 0;
|
||||
do {
|
||||
console.log(j);
|
||||
j++;
|
||||
} while (j < 5);
|
||||
```
|
||||
|
||||
#### Loop control
|
||||
```typescript
|
||||
for (let i = 0; i < 10; i++) {
|
||||
if (i === 3) continue; // Skip iteration
|
||||
if (i === 7) break; // Exit loop
|
||||
console.log(i);
|
||||
}
|
||||
```
|
||||
|
||||
### Function definition
|
||||
|
||||
```typescript
|
||||
// Function declaration
|
||||
function functionName(param1: type, param2: type): returnType {
|
||||
return value;
|
||||
}
|
||||
|
||||
// Function expression
|
||||
const functionName = function(param: type): returnType {
|
||||
return value;
|
||||
};
|
||||
|
||||
// Arrow function
|
||||
const functionName = (param: type): returnType => {
|
||||
return value;
|
||||
};
|
||||
|
||||
// Arrow function (concise)
|
||||
const functionName = (param: type): returnType => value;
|
||||
```
|
||||
|
||||
### Function variations
|
||||
|
||||
```typescript
|
||||
// Optional parameters
|
||||
function greet(name: string, age?: number): string {
|
||||
return age ? `Hello ${name}, you are ${age}` : `Hello ${name}`;
|
||||
}
|
||||
|
||||
// Default parameters
|
||||
function multiply(a: number, b: number = 1): number {
|
||||
return a * b;
|
||||
}
|
||||
|
||||
// Rest parameters
|
||||
function sum(...numbers: number[]): number {
|
||||
return numbers.reduce((total, num) => total + num, 0);
|
||||
}
|
||||
|
||||
// Function overloads
|
||||
function process(input: string): string;
|
||||
function process(input: number): number;
|
||||
function process(input: string | number): string | number {
|
||||
if (typeof input === 'string') {
|
||||
return input.toUpperCase();
|
||||
}
|
||||
return input * 2;
|
||||
}
|
||||
|
||||
// Generic functions
|
||||
function identity<T>(arg: T): T {
|
||||
return arg;
|
||||
}
|
||||
|
||||
let result = identity<string>("hello"); // Type is string
|
||||
let result2 = identity(42); // Type inferred as number
|
||||
```
|
||||
|
||||
### Function call
|
||||
|
||||
```typescript
|
||||
functionName(argument1, argument2);
|
||||
|
||||
// With optional parameters
|
||||
greet("John"); // "Hello John"
|
||||
greet("John", 25); // "Hello John, you are 25"
|
||||
|
||||
// With rest parameters
|
||||
sum(1, 2, 3, 4); // 10
|
||||
|
||||
// Generic function call
|
||||
identity<string>("hello");
|
||||
identity(42); // Type inferred
|
||||
```
|
||||
|
||||
### Classes
|
||||
|
||||
```typescript
|
||||
class ClassName {
|
||||
// Properties
|
||||
public publicProperty: type;
|
||||
private privateProperty: type;
|
||||
protected protectedProperty: type;
|
||||
readonly readonlyProperty: type;
|
||||
static staticProperty: type;
|
||||
|
||||
// Constructor
|
||||
constructor(param: type) {
|
||||
this.publicProperty = param;
|
||||
}
|
||||
|
||||
// Methods
|
||||
public method(): returnType {
|
||||
return value;
|
||||
}
|
||||
|
||||
// Getters and setters
|
||||
get property(): type {
|
||||
return this.privateProperty;
|
||||
}
|
||||
|
||||
set property(value: type) {
|
||||
this.privateProperty = value;
|
||||
}
|
||||
|
||||
// Static method
|
||||
static staticMethod(): returnType {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
// Inheritance
|
||||
class ChildClass extends ParentClass {
|
||||
constructor(param: type) {
|
||||
super(param); // Call parent constructor
|
||||
}
|
||||
|
||||
// Override method
|
||||
method(): returnType {
|
||||
return super.method(); // Call parent method
|
||||
}
|
||||
}
|
||||
|
||||
// Abstract class
|
||||
abstract class AbstractClass {
|
||||
abstract abstractMethod(): void;
|
||||
|
||||
concreteMethod(): void {
|
||||
console.log("This is implemented");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Key TypeScript Features
|
||||
|
||||
* **Static Typing**: Types are checked at compile-time
|
||||
* **Type Inference**: TypeScript can often infer types automatically
|
||||
* **Optional Typing**: You can gradually add types to existing JavaScript
|
||||
* **Generics**: Create reusable components that work with multiple types
|
||||
* **Interfaces**: Define contracts for objects and classes
|
||||
* **Enums**: Create named constants
|
||||
* **Union Types**: Variables can be one of several types
|
||||
* **Intersection Types**: Combine multiple types
|
||||
* **Type Guards**: Runtime type checking
|
||||
* **Decorators**: Add metadata to classes and methods
|
||||
|
||||
### Compilation
|
||||
|
||||
* TypeScript code must be compiled to JavaScript before execution
|
||||
* The TypeScript compiler (`tsc`) performs type checking and transpilation
|
||||
* Configuration is managed through `tsconfig.json`
|
||||
* TypeScript can target different JavaScript versions (ES5, ES6, etc.)
|
||||
* Source maps can be generated for debugging compiled code
|
||||
|
||||
#### Sample TypeScript Code
|
||||
|
||||
**hello.ts**
|
||||
```typescript
|
||||
// TypeScript source code
|
||||
interface User {
|
||||
name: string;
|
||||
age: number;
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
class UserManager {
|
||||
private users: User[] = [];
|
||||
|
||||
addUser(user: User): void {
|
||||
this.users.push(user);
|
||||
console.log(`Added user: ${user.name}`);
|
||||
}
|
||||
|
||||
getActiveUsers(): User[] {
|
||||
return this.users.filter(user => user.isActive ?? true);
|
||||
}
|
||||
|
||||
getUserCount(): number {
|
||||
return this.users.length;
|
||||
}
|
||||
}
|
||||
|
||||
// Generic function
|
||||
function processData<T>(data: T[], processor: (item: T) => T): T[] {
|
||||
return data.map(processor);
|
||||
}
|
||||
|
||||
// Usage
|
||||
const userManager = new UserManager();
|
||||
|
||||
const newUser: User = {
|
||||
name: "John Doe",
|
||||
age: 30,
|
||||
isActive: true
|
||||
};
|
||||
|
||||
userManager.addUser(newUser);
|
||||
|
||||
// Arrow functions with types
|
||||
const formatUser = (user: User): string =>
|
||||
`${user.name} (${user.age} years old)`;
|
||||
|
||||
// Union types and type guards
|
||||
function displayInfo(value: string | number | boolean): string {
|
||||
if (typeof value === "string") {
|
||||
return `Text: ${value.toUpperCase()}`;
|
||||
} else if (typeof value === "number") {
|
||||
return `Number: ${value.toFixed(2)}`;
|
||||
} else {
|
||||
return `Boolean: ${value ? "Yes" : "No"}`;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(displayInfo("hello"));
|
||||
console.log(displayInfo(42.567));
|
||||
console.log(displayInfo(true));
|
||||
```
|
||||
|
||||
#### Compilation Commands
|
||||
|
||||
```bash
|
||||
# Compile single file
|
||||
tsc hello.ts
|
||||
|
||||
# Compile with specific target
|
||||
tsc hello.ts --target ES2020
|
||||
|
||||
# Compile with source maps
|
||||
tsc hello.ts --sourceMap
|
||||
|
||||
# Watch mode (recompile on changes)
|
||||
tsc hello.ts --watch
|
||||
|
||||
# Compile all files in project
|
||||
tsc
|
||||
|
||||
# Check for errors without generating files
|
||||
tsc --noEmit
|
||||
|
||||
# Compile with strict mode
|
||||
tsc hello.ts --strict
|
||||
```
|
||||
|
||||
#### Compiled JavaScript Output
|
||||
|
||||
**hello.js** (compiled from above TypeScript)
|
||||
```javascript
|
||||
"use strict";
|
||||
// JavaScript output (target ES2017)
|
||||
class UserManager {
|
||||
constructor() {
|
||||
this.users = [];
|
||||
}
|
||||
addUser(user) {
|
||||
this.users.push(user);
|
||||
console.log(`Added user: ${user.name}`);
|
||||
}
|
||||
getActiveUsers() {
|
||||
return this.users.filter(user => user.isActive ?? true);
|
||||
}
|
||||
getUserCount() {
|
||||
return this.users.length;
|
||||
}
|
||||
}
|
||||
// Generic function (types removed)
|
||||
function processData(data, processor) {
|
||||
return data.map(processor);
|
||||
}
|
||||
// Usage
|
||||
const userManager = new UserManager();
|
||||
const newUser = {
|
||||
name: "John Doe",
|
||||
age: 30,
|
||||
isActive: true
|
||||
};
|
||||
userManager.addUser(newUser);
|
||||
// Arrow functions
|
||||
const formatUser = (user) => `${user.name} (${user.age} years old)`;
|
||||
// Type guards remain as runtime checks
|
||||
function displayInfo(value) {
|
||||
if (typeof value === "string") {
|
||||
return `Text: ${value.toUpperCase()}`;
|
||||
}
|
||||
else if (typeof value === "number") {
|
||||
return `Number: ${value.toFixed(2)}`;
|
||||
}
|
||||
else {
|
||||
return `Boolean: ${value ? "Yes" : "No"}`;
|
||||
}
|
||||
}
|
||||
console.log(displayInfo("hello"));
|
||||
console.log(displayInfo(42.567));
|
||||
console.log(displayInfo(true));
|
||||
```
|
||||
|
||||
#### tsconfig.json Configuration
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
// Basic Options
|
||||
"target": "ES2020", // Target JavaScript version
|
||||
"module": "commonjs", // Module system
|
||||
"lib": ["ES2020", "DOM"], // Include library files
|
||||
"outDir": "./dist", // Output directory
|
||||
"rootDir": "./src", // Input directory
|
||||
"strict": true, // Enable strict type checking
|
||||
|
||||
// Additional Checks
|
||||
"noUnusedLocals": true, // Error on unused variables
|
||||
"noUnusedParameters": true, // Error on unused parameters
|
||||
"noImplicitReturns": true, // Error on missing return statements
|
||||
"noFallthroughCasesInSwitch": true, // Error on fallthrough cases
|
||||
|
||||
// Module Resolution
|
||||
"moduleResolution": "node", // Module resolution strategy
|
||||
"baseUrl": "./", // Base directory
|
||||
"paths": { // Path mapping
|
||||
"@/*": ["src/*"],
|
||||
"@utils/*": ["src/utils/*"]
|
||||
},
|
||||
|
||||
// Source Maps & Debugging
|
||||
"sourceMap": true, // Generate source maps
|
||||
"inlineSourceMap": false, // Don't inline source maps
|
||||
"declaration": true, // Generate .d.ts files
|
||||
"declarationMap": true, // Generate .d.ts.map files
|
||||
|
||||
// Experimental
|
||||
"experimentalDecorators": true, // Enable decorators
|
||||
"emitDecoratorMetadata": true, // Emit decorator metadata
|
||||
|
||||
// JavaScript Support
|
||||
"allowJs": true, // Allow JavaScript files
|
||||
"checkJs": false, // Type check JavaScript files
|
||||
|
||||
// Other Options
|
||||
"esModuleInterop": true, // CommonJS/ES6 interop
|
||||
"skipLibCheck": true, // Skip lib.d.ts type checking
|
||||
"forceConsistentCasingInFileNames": true, // Consistent file names
|
||||
"removeComments": true, // Remove comments from output
|
||||
"noEmitOnError": true // Don't emit if there are errors
|
||||
},
|
||||
"include": [
|
||||
"src/**/*", // Include all files in src
|
||||
"tests/**/*" // Include test files
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules", // Exclude node_modules
|
||||
"dist", // Exclude output directory
|
||||
"**/*.test.ts", // Exclude test files from compilation
|
||||
"**/*.spec.ts"
|
||||
],
|
||||
"files": [
|
||||
// Explicitly include specific files (optional)
|
||||
"src/main.ts"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Package.json Scripts
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "typescript-project",
|
||||
"version": "1.0.0",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"start": "node dist/main.js",
|
||||
"dev": "ts-node src/main.ts",
|
||||
"watch": "tsc --watch",
|
||||
"clean": "rm -rf dist",
|
||||
"type-check": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^4.9.0",
|
||||
"ts-node": "^10.9.0",
|
||||
"@types/node": "^18.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Compilation Examples with Different Targets
|
||||
|
||||
**Original TypeScript:**
|
||||
```typescript
|
||||
const greet = (name: string = "World"): string => `Hello, ${name}!`;
|
||||
const user = { name: "Alice", age: 30 };
|
||||
const { name, age } = user;
|
||||
```
|
||||
|
||||
**Compiled to ES5:**
|
||||
```javascript
|
||||
var greet = function (name) {
|
||||
if (name === void 0) { name = "World"; }
|
||||
return "Hello, " + name + "!";
|
||||
};
|
||||
var user = { name: "Alice", age: 30 };
|
||||
var name = user.name, age = user.age;
|
||||
```
|
||||
|
||||
**Compiled to ES2020:**
|
||||
```javascript
|
||||
const greet = (name = "World") => `Hello, ${name}!`;
|
||||
const user = { name: "Alice", age: 30 };
|
||||
const { name, age } = user;
|
||||
```
|
||||
|
||||
#### Error Examples
|
||||
|
||||
**TypeScript with errors:**
|
||||
```typescript
|
||||
// Type errors that prevent compilation
|
||||
let message: string = 42; // Error: Type 'number' is not assignable to type 'string'
|
||||
let numbers: number[] = ["a", "b"]; // Error: Type 'string' is not assignable to type 'number'
|
||||
|
||||
function add(a: number, b: number): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
add("hello", "world"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'
|
||||
```
|
||||
|
||||
**Compiler output:**
|
||||
```bash
|
||||
$ tsc error-example.ts
|
||||
error-example.ts(2,5): error TS2322: Type 'number' is not assignable to type 'string'.
|
||||
error-example.ts(3,5): error TS2322: Type 'string[]' is not assignable to type 'number[]'.
|
||||
error-example.ts(8,5): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
|
||||
```
|
||||
@@ -21,7 +21,6 @@ cat /proc/<process_id>/maps # Show the current virtual memory usage of a Linux
|
||||
ip r # Display ip of the server
|
||||
|
||||
lsof -i :9000 # List process running on port 9000
|
||||
kill -9 $(lsof -t -i:PORT) # Kill the process running on whichever port specified
|
||||
|
||||
journalctl -u minio.service -n 100 --no-pager # List last 100 logs for specific service
|
||||
|
||||
|
||||
Reference in New Issue
Block a user