SlideShare a Scribd company logo
Babel Coder
RECAP JAVASCRIPT
Babel Coder
TEMPLATE
Template String
var myStr1 = 'Hello World'
var myStr2 = "Hello World"
var myStr3 = "HellonWorld"
var myStr4 = `
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
`
var myStr5 = `${myStr1} Krub`
Babel Coder
LET AND CONST
function foo() {
let x = 1
x = 2
}
foo()
function foo() {
const x = 1
x = 2
}
foo()
Babel Coder
PROPERTY SHORTHAND
const x = 10
const y = 20
const obj = { x: x, y: y }
const obj = { x, y } Property Shorthand (ES6+)
Babel Coder
DESTRUCTURING
let person = {
age: 24,
gender: 'male',
name: {
fi
rstName: '
fi
rstName',
lastName: 'lastName'
}
}
let age = person.age
let gender = person.gender
let name = person.name
let
fi
rstName = name.
fi
rstName
let lastName = name.lastName
let { age, gender, name } = person
let {
fi
rstName, lastName } = name
let { age, gender, name: {
fi
rstName, lastName } } = person
Babel Coder
SPREAD OPERATORS
const obj1 = { a: 1, b: 2 }
const obj2 = { c: 3, d: 4 }
console.log({ ...obj1, ...obj2 })
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
console.log([...arr1, ...arr2])
Babel Coder
EXAMPLE 1
Math.min(12, 14, 8, 17, 21, 9) // 8
const nums = [12, 14, 8, 17, 21, 9]
Math.min(...nums)
Babel Coder
ARROW FUNCTION
function foo(a) {
return a + 1
}
const foo = (a) => {
return a + 1
}
const foo = a => {
return a + 1
}
const foo = a => a + 1
const foo = a => let b = a + 1 Must be expression
OPTIONAL CHAINING
const person = {
name: 'Somchai',
age: 24,
socials: {
facebook: 'somchai24'
}
}
<div>
<div>{person?.socials?.facebook}</div>
</div>
<div>
<div>{person?.tel?.phone}</div>
</div>
ES MODULE - NAMED EXPORTS
export const DEFAULT_COLOR = 'white'
export function walk() {
console.log('Walking...')
}
{
DEFAULT_COLOR: 'white',
walk() {
console.log('Walking...')
}
}
dog.js
main.js
syntax: 1
import * as lib from './dog.js'
lib.DEFAULT_COLOR // white
lib.walk() // Walking...
main.js
syntax: 2
import { DEFAULT_COLOR, walk } from './dog.js'
ES MODULE - DEFAULT EXPORT
circle.js
main.js
syntax
export default class Circle {
area() {
}
}
import Circle from './circle.js'
ES MODULE - BOTH
circle.js
export const PI = 3.14
export default class Circle {
area() {
}
}
main.js
syntax
import Circle, { PI } from './circle.js'
Babel Coder
FETCHING
fetch('/api/v1/articles/1', function(response) {
fetch('/api/v1/users/' + response.authorId, function(response) {
// ...
})
})
fetch('/api/v1/articles/1')
.then(function(response) {
return fetch('/api/v1/users/' + response.authorId)
})
.then(function() { })
Babel Coder
AXIOS
import axios from 'axios'
axios.get('/articles')
.then(res => console.log(res.data))
axios.post('/articles', { title: 'Title#1', content: 'Content#1' })
.then(res => console.log(res.data))
GET
POST
Babel Coder
AXIOS BASE URL AND INTERCEPTORS
axios.defaults.baseURL = 'https://api.example.com'
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
// Interceptors
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
auth.clearAuth()
router.replace('/signin')
}
return Promise.reject(error.response)
}
)
ASYNC / AWAIT
promise.then(function(result) {
console.log(result)
}).catch(function(error) {
console.log(error)
})
async function doAsync() {
try {
const result = await promise
console.log(result)
} catch(error) {
console.log(error)
}
}
EXAMPLE 1
Fetch content from URL: https://jsonplaceholder.typicode.com/todos
import axios from 'axios'
async function fetchPosts() {
const res =await axios.get(URL)
console.log(res.data)
console.log(res.status) // 200
}
fetchPosts()
HTTP GET HTTP POST
import axios from 'axios'
async function createPost() {
const res =await axios.post(
URL, { title: 'Test', completed: true })
console.log(res.status) // 201
}
createPost()
WHAT IS FUNCTIONAL PROGRAMMING
• Functional Programming is a programming paradigm.
• It treats computation as the evaluation of mathematical functions.
• Avoid changing state.
• Eliminating side effects of function calls.
• Declarative Style
IMMUTABILITY
const nums = [1, 2, 3]
const nums2 = [6, 7]
nums.concat()
nums.slice()
nums.concat(4) // [1, 2, 3, 4]
nums.slice(0, 2); // [1, 2]
[...nums, 4, ...nums2]
// [1, 2, 3, 4, 6, 7]
const object = { a: 1, b: 2 }
// {"a":1,"b":2,"c":3,"d":4}
console.log({...object, c: 3, d: 4 })
// {"a":1,"b":9}
const newObject = { b: 9 }
console.log({ ...object, ...newObject })
// {"a":1,"b":9}
const key = 'b'
console.log({ ...object, [key]: 9})
1
MAP
const nums = [1, 2, 3]
console.log(nums.map(num => num * 2)) //
[2, 4, 6]
const students = [
{ id: 1, advisorId: 1 },
{ id: 2, advisorId: 2 },
{ id: 3, advisorId: 3 },
{ id: 4, advisorId: 1 },
{ id: 5, advisorId: 3 }
]
console.log(
students.map(student =>
student.advisorId === 1 ?
{ ...student, advisorId: 2 } :
student
)
)
// [{"id":1,"advisorId":2},
{"id":2,"advisorId":2}, {"id":3,"advisorId":3},
{"id":4,"advisorId":2}, {"id":5,"advisorId":3}]
2
FILTER
const students = [
{ id: 1, advisorId: 1 },
{ id: 2, advisorId: 2 },
{ id: 3, advisorId: 3 },
{ id: 4, advisorId: 1 },
{ id: 5, advisorId: 3 }
]
console.log(
students.filter(student => student.advisorId === 1)
)
// [{"id":1,"advisorId":1},{"id":4,"advisorId":1}]
3
FIND / FIND INDEX
const nums = [1, 2, 3, 4, 5]
nums.find(num => num % 2 === 0) // 2
const nums = [1, 2, 3, 4, 5]
nums.findIndex(num => num % 2 === 0) // 1
4
Babel Coder
INTRODUCTION TO
TYPESCRIPT
Babel Coder
SETUP
1 yarn init -y
2 yarn add -D tsc nodemon ts-node typescript eslint eslint-con g-prettier eslint-plugin-prettier prettier
@typescript-eslint/parser @typescript-eslint/eslint-plugin
3 npx tsc —init
4 package.json
"scripts": {
"dev": "nodemon src/index.ts",
"build": "tsc",
"lint": "eslint '*/**/*.{js,ts}' --quiet --
fi
x"
},
Babel Coder
SETUP
5 .eslintrc.js
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
},
settings: {},
extends: [
'plugin:@typescript-eslint/recommended',
'prettier/@typescript-eslint',
'plugin:prettier/recommended',
],
rules: {},
};
6 .vscode/settings.json
{
"editor.tabSize": 2,
"editor.codeActionsOnSave": {
"source.
fi
xAll.eslint": true
}
}
Babel Coder
SETUP
7 .prettierrc
{
"trailingComma": "all",
"singleQuote": true
}
8 nodemon.json
{
"watch": ["src"],
"ext": "ts",
"exec": "ts-node"
}
9 tscon
fi
g.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["ES2020", "DOM"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Babel Coder
SETUP
Babel Coder
PRIMITIVE DATA TYPES
• string
• number
• bigint
• boolean
• null
• undefined
• symbol
Babel Coder
PRIMITIVE DATA TYPES
const num1: number = 10
const num2 = 20
const bool1: boolean = true
const bool2 = false
const str1: string = "hello"
const str2 = "world"
Babel Coder
ANY AND UNKNOWN
function next(num: number) {
return num + 1;
}
let num: any = 10;
num = 'hello';
next(num);
num.toFixed(2);
let num: unknown = 10;
num = 'hello';
// Argument of type 'unknown' is not assignable to parameter of type 'number'.
next(num);
// Object is of type 'unknown'.
num.toFixed(2);
const num: unknown = 10;
next(num);
if (typeof num === 'number') {
next(num);
}
Babel Coder
LITERAL TYPES
let str1: 'Hello' = 'Hello';
let str2: string = str1;
// Type 'string' is not assignable to type '"Hello"'.
str1 = str2;
let str1 = 'Hello'; // string
const str2 = 'Hello'; // Hello
function permission(role: 'Admin' | 'Moderator' | 'Editor') {
// do sth
}
permission('Admin');
let role = 'Editor';
// Argument of type 'string' is not assignable
// to parameter of type '"Admin" | "Moderator" | "Editor"'.
permission(role);
permission(role as 'Editor');
Babel Coder
ARRAY
let nums1: number[] = [1, 2, 3] // number[]
let nums2: Array<number> = [1, 2, 3] // number[]
let nums3 = [1, 2, 3] // number[]
const nums4 = [1, 2, 3] // number[]
const nums5: readonly number[] = [1, 2, 3] // readonly number[]
const nums6: ReadonlyArray<number> = [1, 2, 3] // readonly number[]
const nums7 = nums6 as number[]; // number[]
const foo: string[] = []; // OK
const a: never[] = []; // OK
const b: never[] = [1, 2]; // Type 'number' is not assignable to type 'never'
Babel Coder
ENUM
enum Role {
Admin,
Moderator,
Editor,
}
const myRole: Role = Role.Admin; // 0
Role[0]; // Admin
Role.Admin // 0
enum Role {
Admin,
Moderator,
Editor,
}
enum Role {
Admin = 'Admin',
Moderator = 'Moderator',
Editor = 'Editor',
}
Role.Admin; // Admin
Babel Coder
INTERFACES
let person; // any
person = {
name: 'Somchai',
age: 24,
gender: 'male',
};
interface Person {
name: string;
age: number;
gender: string;
}
let person: Person;
person = {
name: 'Somchai',
age: 24,
gender: 'male',
};
// Property 'gender' is missing in type
// ‘{ name: string; age: number; }'
// but required in type 'Person'.
const person: Person = {
name: 'Somchai',
age: 24,
};
const person: Person = {
name: 'Somchai',
age: 24,
gender: 'male',
};
Babel Coder
EXTENDING INTERFACES
interface Website {
url: string;
}
interface Article {
title: string;
content: string;
}
interface BlogPost extends Website, Article {
view: number;
}
const post: BlogPost = {
url: 'https://www.babelcoder.com/blog/articles/typescript-classes',
title: 'การใ
ช้
งานคลาสใน TypeScript',
content: '...',
view: 999,
};
Babel Coder
READONLY AND OPTIONAL PROPERTIES
interface Person {
fi
rstName: string;
lastName: string;
middleName?: string;
readonly gender: 'Male' | 'Female';
}
let somchai: Person = {
fi
rstName: 'Somchai',
lastName: 'Haha',
gender: 'Male',
};
// Cannot assign to 'gender' because
// it is a read-only property.
somchai.gender = 'Female';
Babel Coder
TYPE ALIAS
interface Person {
name: string;
age: number;
gender: string;
}
type Person = {
name: string;
age: number;
gender: string;
};
interface Website {
url: string;
}
interface Article {
title: string;
content: string;
}
interface BlogPost extends Website, Article {
view: number;
}
type Website = {
url: string;
};
type Article = {
title: string;
content: string;
};
type BlogPost = Website &
Article & {
view: number;
};
Babel Coder
FUNCTION TYPES
function getFullName(
fi
rstName, lastName) {
return `${
fi
rstName} ${lastName}`;
}
function getFullName( fi
rstName: string, lastName: string): string {
return `${
fi
rstName} ${lastName}`;
}
const getFullName = function (
fi
rstName: string, lastName: string): string {
return `${
fi
rstName} ${lastName}`;
};
Babel Coder
FUNCTION TYPES
const getFullName = (
fi
rstName, lastName) => {
return `${
fi
rstName} ${lastName}`;
};
const getFullName = ( fi
rstName: string, lastName: string): string => {
return `${
fi
rstName} ${lastName}`;
};
type GetFullNameFn = (
fi
rstName: string, lastName: string) => string;
const getFullName: GetFullNameFn = (
fi
rstName, lastName) => {
return `${
fi
rstName} ${lastName}`;
};
Babel Coder
CONST ASSERTIONS
// const theme: {
// colors: {
// amethyst: "#9b59b6";
// carrot: string;
// };
// }
const theme = {
colors: {
amethyst: '#9b59b6' as const,
carrot: '#e67e22',
},
};
// const theme: {
// colors: {
// amethyst: string;
// carrot: string;
// };
// }
const theme = {
colors: {
amethyst: '#9b59b6',
carrot: '#e67e22',
},
};
// const theme: {
// readonly colors: {
// readonly amethyst: "#9b59b6";
// readonly carrot: "#e67e22";
// };
// }
const theme = {
colors: {
amethyst: '#9b59b6',
carrot: '#e67e22',
},
} as const;
Babel Coder
TYPEOF
const user = { name: 'Somchai' };
console.log(typeof user); // 'object'
// type User = {
// name: string;
// }
type User = typeof user;
Babel Coder
UNION TYPES
type Printable = string | string[];
const text: Printable = 'my message';
function format(thing: Printable): string {
if (Array.isArray(thing)) return thing.join(', ');
return thing;
}
Babel Coder
INTERSECTION TYPES
interface Identity {
id: number;
name: string;
}
interface Contact {
email: string;
phone: string;
address: string;
}
type Employee = Identity & Contact;
const somchai: Employee = {
id: 11001,
name: 'Somchai',
email: 'somchai@haha.com',
phone: '082-111-1111',
address: '111/11',
};
Babel Coder
CLASSES
class BankAccount {
static interestRate = 3.5;
balance: number;
constructor(balance: number) {
this.balance = balance;
}
getInterest() {
return this.balance * BankAccount.interestRate;
}
}
const myAcc1 = new BankAccount(20);
const myAcc2 = new BankAccount(30);
myAcc1.balance; // 20
myAcc1.getInterest(); // 70
myAcc1
balance: 20
getInterest
myAcc2
balance: 30
getInterest
getInterest
3.5
BankAccount
Babel Coder
ACCESS MODIFIERS
class BankAccount {
protected balance: number;
constructor(balance: number) {
this.balance = balance;
}
withdraw(amount: number) {
if (amount <= this.balance) this.balance -= amount;
}
deposit(amount: number) {
if (amount > 0) this.balance += amount;
}
}
class SavingAccount extends BankAccount {
static readonly interestRate = 3.5;
private readonly debitCard: number;
constructor(balance: number, debitCard: number) {
super(balance);
this.debitCard = debitCard;
}
getInterest() {
return this.balance * SavingAccount.interestRate;
}
}
Babel Coder
PARAMETER PROPERTIES
class BankAccount {
constructor(protected balance: number) {}
withdraw(amount: number) {
if (amount <= this.balance) this.balance -= amount;
}
deposit(amount: number) {
if (amount > 0) this.balance += amount;
}
}
class SavingAccount extends BankAccount {
static interestRate = 3.5;
constructor(
balance: number,
private readonly debitCard: number) {
super(balance);
}
getInterest() {
return this.balance * SavingAccount.interestRate;
}
}
Babel Coder
KEYWORD NEW
class Person {
constructor() {}
}
function get<T>(ctor: Factory<T>) {
return new ctor();
}
// const person: Person
const person = get(Person);
interface Factory<T> {
new (...args: any[]): T;
}
// OR
type Factory<T> = new (...args: any[]) => T;
Babel Coder
GENERIC FUNCTIONS
function lastNum(arr: number[], count: number) {
return arr.slice(arr.length - count);
}
lastNum([1, 2, 3, 4, 5], 3); // [3, 4, 5]
function lastStr(arr: string[], count: number) {
return arr.slice(arr.length - count);
}
lastStr(['A', 'B', 'C', 'D', 'E'], 2); // ['D', 'E']
function last<T>(arr: T[], count: number) {
return arr.slice(arr.length - count);
}
const last = <T>(arr: T[], count: number) => {
return arr.slice(arr.length - count);
};
last<string>(['A', 'B', 'C', 'D', 'E'], 2);
last(['A', 'B', 'C', 'D', 'E'], 2);
Babel Coder
GENERIC TYPES AND INTERFACES
const head = <T>(arr: T[]) => arr[0];
const tail = <T>(arr: T[]) => arr[arr.length - 1];
type GetItem<T> = (arr: T[]) => T;
interface GetItem<T> {
(arr: T[]): T;
}
const option: GetItem<number> = head;
option([1, 2, 3]);
function getItem<T>(list: T[], fn: GetItem<T>): T {
return fn(list);
}
getItem([1, 2, 3], head); // 1
getItem([1, 2, 3], tail); // 3
Babel Coder
UTILITY TYPES
Babel Coder
RECORD
type MyRecord<T extends string | number | symbol, U> = {
[K in T]: U;
};
type keys = 'name' | 'address';
// type MyPerson = {
// name: string;
// address: string;
// }
type MyPerson = MyRecord<keys, string>;
type Person = Record<keys, string>;
Babel Coder
PICK AND OMIT
type MyPick<T, K extends keyof T> = {
[P in K]: T[P];
};
type Person = {
name: string;
age: number;
address: string;
};
// type NameAndAge = {
// name: string;
// age: number;
// }
type MyNameAndAge = MyPick<Person, 'name' | 'age'>;
type NameAndAge = Pick<Person, 'name' | 'age'>;
type MyOmit<T, K extends string | number | symbol> = Pick<
T,
Exclude<keyof T, K>
>;
type Person = {
name: string;
age: number;
address: string;
};
// type MyAddress = {
// address: string;
// }
type MyAddress = MyOmit<Person, 'name' | 'age'>;
type Address = Omit<Person, 'name' | 'age'>;
Babel Coder
REQUIRED AND PARTIAL
type MyPartial<T> = {
[K in keyof T]?: T[K];
};
type Person = {
name: string;
age: number;
address: string;
};
// type MyPartialPerson = {
// name?: string | unde
fi
ned;
// age?: number | unde
fi
ned;
// address?: string | unde
fi
ned;
// }
type MyPartialPerson = MyPartial<Person>;
type PartialPerson = Partial<Person>;
type MyRequired<T> = {
[K in keyof T]-?: T[K];
};
type Person = {
name: string;
age: number;
address: string;
};
// type MyRequiredPerson = {
// name: string;
// age: number;
// address: string;
// }
type MyRequiredPerson = MyRequired<Person>;
type RequiredPerson = Required<Person>;
Babel Coder
READONLY
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
type Person = {
name: string;
age: number;
address: string;
};
// type MyReadOnlyPerson = {
// readonly name: string;
// readonly age: number;
// readonly address: string;
// }
type MyReadOnlyPerson = MyReadonly<Person>;
type ReadOnlyPerson = Readonly<Person>;
Babel Coder
DECLARATION FILES
Babel Coder
DEFINITELY TYPED
// Could not
fi
nd a declaration
fi
le for module 'lodash'.
import lodash from 'lodash';
yarn add @types/lodash
yarn add @types/absinthe__socket

More Related Content

PDF
Tizen RT: A Lightweight RTOS Platform for Low-End IoT Devices
DOCX
Study guide for quiz 3
PPTX
Recent advances in diagnosis of hemoparasite infections
PDF
recap-js-and-ts.pdf
PDF
recap-ts.pdf
PDF
recap-js.pdf
PPTX
Academy PRO: ES2015
PDF
Clean & Typechecked JS
Tizen RT: A Lightweight RTOS Platform for Low-End IoT Devices
Study guide for quiz 3
Recent advances in diagnosis of hemoparasite infections
recap-js-and-ts.pdf
recap-ts.pdf
recap-js.pdf
Academy PRO: ES2015
Clean & Typechecked JS

Similar to ts+js (20)

PDF
javascript for modern application.pdf
PDF
ES6 General Introduction
PDF
Workshop 10: ECMAScript 6
PDF
Introduction to ECMAScript 2015
PDF
Modern Application Foundations: Underscore and Twitter Bootstrap
PDF
Introduction to ES2015
PDF
Essentials and Impactful Features of ES6
ODP
ES6 PPT FOR 2016
PDF
Static types on javascript?! Type checking approaches to ensure healthy appli...
ODP
EcmaScript 6
PDF
Explaining ES6: JavaScript History and What is to Come
PDF
Es6 to es5
PPTX
Ecmascript 6
PDF
Intro to React
PDF
Idiomatic Javascript (ES5 to ES2015+)
PDF
Reason - introduction to language and its ecosystem | Łukasz Strączyński
PDF
ECMAScript2015
PDF
Introduction to Swift 2
PDF
BabelJS - James Kyle at Modern Web UI
PDF
Swift Programming
javascript for modern application.pdf
ES6 General Introduction
Workshop 10: ECMAScript 6
Introduction to ECMAScript 2015
Modern Application Foundations: Underscore and Twitter Bootstrap
Introduction to ES2015
Essentials and Impactful Features of ES6
ES6 PPT FOR 2016
Static types on javascript?! Type checking approaches to ensure healthy appli...
EcmaScript 6
Explaining ES6: JavaScript History and What is to Come
Es6 to es5
Ecmascript 6
Intro to React
Idiomatic Javascript (ES5 to ES2015+)
Reason - introduction to language and its ecosystem | Łukasz Strączyński
ECMAScript2015
Introduction to Swift 2
BabelJS - James Kyle at Modern Web UI
Swift Programming
Ad

More from NuttavutThongjor1 (20)

PDF
Modern DevOps Day 5.pdfModern DevOps Day 5.pdf
PDF
Modern DevOps Day 4.pdfModern DevOps Day 4.pdf
PDF
Modern DevOps Day 3.pdfModern DevOps Day 3.pdf
PDF
Modern DevOps Day 2.pdfModern DevOps Day 2.pdf
PDF
Modern DevOps Day 1.pdfModern DevOps Day 1.pdfModern DevOps Day 1.pdf
PDF
misc.pdfmisc.pdfmisc.pdfmisc.pdfmisc.pdfmisc.pdfmisc.pdfmisc.pdfmisc.pdfmisc.pdf
PDF
Nest.js Microservices (1).pdf Nest.js Microservices (1).pdfNest.js Microservi...
PDF
Nest.js Microservices.pdfNest.js Microservices.pdfNest.js Microservices.pdfNe...
PDF
GraphQL.pdfGraphQL.pdfGraphQL.pdfGraphQL.pdfGraphQL.pdfGraphQL.pdf
PDF
Nest.js RESTful API development.pdf Nest.js RESTful API development.pdf
PDF
Nest.js RESTful API development.pdfNest.js RESTful API development.pdf
PDF
Recap JavaScript and TypeScript.pdf Recap JavaScript and TypeScript.pdf
PDF
Next.js web development.pdfNext.js web development.pdfNext.js web development...
PDF
Next.js web development.pdfNext.js web development.pdfNext.js web development...
PDF
Fullstack Nest.js and Next.js.pdfFullstack Nest.js and Next.js.pdfFullstack N...
PDF
Recap JavaScript and TypeScript.pdf Recap JavaScript and TypeScript.pdf
PDF
Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
PDF
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
PDF
9 logging and monitoring.pdf 9 logging and monitoring.pdf
PDF
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
Modern DevOps Day 5.pdfModern DevOps Day 5.pdf
Modern DevOps Day 4.pdfModern DevOps Day 4.pdf
Modern DevOps Day 3.pdfModern DevOps Day 3.pdf
Modern DevOps Day 2.pdfModern DevOps Day 2.pdf
Modern DevOps Day 1.pdfModern DevOps Day 1.pdfModern DevOps Day 1.pdf
misc.pdfmisc.pdfmisc.pdfmisc.pdfmisc.pdfmisc.pdfmisc.pdfmisc.pdfmisc.pdfmisc.pdf
Nest.js Microservices (1).pdf Nest.js Microservices (1).pdfNest.js Microservi...
Nest.js Microservices.pdfNest.js Microservices.pdfNest.js Microservices.pdfNe...
GraphQL.pdfGraphQL.pdfGraphQL.pdfGraphQL.pdfGraphQL.pdfGraphQL.pdf
Nest.js RESTful API development.pdf Nest.js RESTful API development.pdf
Nest.js RESTful API development.pdfNest.js RESTful API development.pdf
Recap JavaScript and TypeScript.pdf Recap JavaScript and TypeScript.pdf
Next.js web development.pdfNext.js web development.pdfNext.js web development...
Next.js web development.pdfNext.js web development.pdfNext.js web development...
Fullstack Nest.js and Next.js.pdfFullstack Nest.js and Next.js.pdfFullstack N...
Recap JavaScript and TypeScript.pdf Recap JavaScript and TypeScript.pdf
Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
9 logging and monitoring.pdf 9 logging and monitoring.pdf
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
Ad

Recently uploaded (20)

PDF
RMMM.pdf make it easy to upload and study
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PPTX
Unit 4 Skeletal System.ppt.pptxopresentatiom
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PDF
Indian roads congress 037 - 2012 Flexible pavement
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PDF
Trump Administration's workforce development strategy
PPTX
Digestion and Absorption of Carbohydrates, Proteina and Fats
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
1_English_Language_Set_2.pdf probationary
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Complications of Minimal Access Surgery at WLH
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
RMMM.pdf make it easy to upload and study
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Paper A Mock Exam 9_ Attempt review.pdf.
Unit 4 Skeletal System.ppt.pptxopresentatiom
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
Indian roads congress 037 - 2012 Flexible pavement
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
Trump Administration's workforce development strategy
Digestion and Absorption of Carbohydrates, Proteina and Fats
202450812 BayCHI UCSC-SV 20250812 v17.pptx
History, Philosophy and sociology of education (1).pptx
1_English_Language_Set_2.pdf probationary
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
Final Presentation General Medicine 03-08-2024.pptx
Complications of Minimal Access Surgery at WLH
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
LDMMIA Reiki Yoga Finals Review Spring Summer
A powerpoint presentation on the Revised K-10 Science Shaping Paper
Orientation - ARALprogram of Deped to the Parents.pptx

ts+js

  • 2. Babel Coder TEMPLATE Template String var myStr1 = 'Hello World' var myStr2 = "Hello World" var myStr3 = "HellonWorld" var myStr4 = ` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ` var myStr5 = `${myStr1} Krub`
  • 3. Babel Coder LET AND CONST function foo() { let x = 1 x = 2 } foo() function foo() { const x = 1 x = 2 } foo()
  • 4. Babel Coder PROPERTY SHORTHAND const x = 10 const y = 20 const obj = { x: x, y: y } const obj = { x, y } Property Shorthand (ES6+)
  • 5. Babel Coder DESTRUCTURING let person = { age: 24, gender: 'male', name: { fi rstName: ' fi rstName', lastName: 'lastName' } } let age = person.age let gender = person.gender let name = person.name let fi rstName = name. fi rstName let lastName = name.lastName let { age, gender, name } = person let { fi rstName, lastName } = name let { age, gender, name: { fi rstName, lastName } } = person
  • 6. Babel Coder SPREAD OPERATORS const obj1 = { a: 1, b: 2 } const obj2 = { c: 3, d: 4 } console.log({ ...obj1, ...obj2 }) const arr1 = [1, 2, 3] const arr2 = [4, 5, 6] console.log([...arr1, ...arr2])
  • 7. Babel Coder EXAMPLE 1 Math.min(12, 14, 8, 17, 21, 9) // 8 const nums = [12, 14, 8, 17, 21, 9] Math.min(...nums)
  • 8. Babel Coder ARROW FUNCTION function foo(a) { return a + 1 } const foo = (a) => { return a + 1 } const foo = a => { return a + 1 } const foo = a => a + 1 const foo = a => let b = a + 1 Must be expression
  • 9. OPTIONAL CHAINING const person = { name: 'Somchai', age: 24, socials: { facebook: 'somchai24' } } <div> <div>{person?.socials?.facebook}</div> </div> <div> <div>{person?.tel?.phone}</div> </div>
  • 10. ES MODULE - NAMED EXPORTS export const DEFAULT_COLOR = 'white' export function walk() { console.log('Walking...') } { DEFAULT_COLOR: 'white', walk() { console.log('Walking...') } } dog.js main.js syntax: 1 import * as lib from './dog.js' lib.DEFAULT_COLOR // white lib.walk() // Walking... main.js syntax: 2 import { DEFAULT_COLOR, walk } from './dog.js'
  • 11. ES MODULE - DEFAULT EXPORT circle.js main.js syntax export default class Circle { area() { } } import Circle from './circle.js'
  • 12. ES MODULE - BOTH circle.js export const PI = 3.14 export default class Circle { area() { } } main.js syntax import Circle, { PI } from './circle.js'
  • 13. Babel Coder FETCHING fetch('/api/v1/articles/1', function(response) { fetch('/api/v1/users/' + response.authorId, function(response) { // ... }) }) fetch('/api/v1/articles/1') .then(function(response) { return fetch('/api/v1/users/' + response.authorId) }) .then(function() { })
  • 14. Babel Coder AXIOS import axios from 'axios' axios.get('/articles') .then(res => console.log(res.data)) axios.post('/articles', { title: 'Title#1', content: 'Content#1' }) .then(res => console.log(res.data)) GET POST
  • 15. Babel Coder AXIOS BASE URL AND INTERCEPTORS axios.defaults.baseURL = 'https://api.example.com' axios.defaults.headers.common['Authorization'] = AUTH_TOKEN // Interceptors axios.interceptors.response.use( response => response, error => { if (error.response.status === 401) { auth.clearAuth() router.replace('/signin') } return Promise.reject(error.response) } )
  • 16. ASYNC / AWAIT promise.then(function(result) { console.log(result) }).catch(function(error) { console.log(error) }) async function doAsync() { try { const result = await promise console.log(result) } catch(error) { console.log(error) } }
  • 17. EXAMPLE 1 Fetch content from URL: https://jsonplaceholder.typicode.com/todos import axios from 'axios' async function fetchPosts() { const res =await axios.get(URL) console.log(res.data) console.log(res.status) // 200 } fetchPosts() HTTP GET HTTP POST import axios from 'axios' async function createPost() { const res =await axios.post( URL, { title: 'Test', completed: true }) console.log(res.status) // 201 } createPost()
  • 18. WHAT IS FUNCTIONAL PROGRAMMING • Functional Programming is a programming paradigm. • It treats computation as the evaluation of mathematical functions. • Avoid changing state. • Eliminating side effects of function calls. • Declarative Style
  • 19. IMMUTABILITY const nums = [1, 2, 3] const nums2 = [6, 7] nums.concat() nums.slice() nums.concat(4) // [1, 2, 3, 4] nums.slice(0, 2); // [1, 2] [...nums, 4, ...nums2] // [1, 2, 3, 4, 6, 7] const object = { a: 1, b: 2 } // {"a":1,"b":2,"c":3,"d":4} console.log({...object, c: 3, d: 4 }) // {"a":1,"b":9} const newObject = { b: 9 } console.log({ ...object, ...newObject }) // {"a":1,"b":9} const key = 'b' console.log({ ...object, [key]: 9}) 1
  • 20. MAP const nums = [1, 2, 3] console.log(nums.map(num => num * 2)) // [2, 4, 6] const students = [ { id: 1, advisorId: 1 }, { id: 2, advisorId: 2 }, { id: 3, advisorId: 3 }, { id: 4, advisorId: 1 }, { id: 5, advisorId: 3 } ] console.log( students.map(student => student.advisorId === 1 ? { ...student, advisorId: 2 } : student ) ) // [{"id":1,"advisorId":2}, {"id":2,"advisorId":2}, {"id":3,"advisorId":3}, {"id":4,"advisorId":2}, {"id":5,"advisorId":3}] 2
  • 21. FILTER const students = [ { id: 1, advisorId: 1 }, { id: 2, advisorId: 2 }, { id: 3, advisorId: 3 }, { id: 4, advisorId: 1 }, { id: 5, advisorId: 3 } ] console.log( students.filter(student => student.advisorId === 1) ) // [{"id":1,"advisorId":1},{"id":4,"advisorId":1}] 3
  • 22. FIND / FIND INDEX const nums = [1, 2, 3, 4, 5] nums.find(num => num % 2 === 0) // 2 const nums = [1, 2, 3, 4, 5] nums.findIndex(num => num % 2 === 0) // 1 4
  • 24. Babel Coder SETUP 1 yarn init -y 2 yarn add -D tsc nodemon ts-node typescript eslint eslint-con g-prettier eslint-plugin-prettier prettier @typescript-eslint/parser @typescript-eslint/eslint-plugin 3 npx tsc —init 4 package.json "scripts": { "dev": "nodemon src/index.ts", "build": "tsc", "lint": "eslint '*/**/*.{js,ts}' --quiet -- fi x" },
  • 25. Babel Coder SETUP 5 .eslintrc.js module.exports = { parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 2020, sourceType: 'module', }, settings: {}, extends: [ 'plugin:@typescript-eslint/recommended', 'prettier/@typescript-eslint', 'plugin:prettier/recommended', ], rules: {}, }; 6 .vscode/settings.json { "editor.tabSize": 2, "editor.codeActionsOnSave": { "source. fi xAll.eslint": true } }
  • 26. Babel Coder SETUP 7 .prettierrc { "trailingComma": "all", "singleQuote": true } 8 nodemon.json { "watch": ["src"], "ext": "ts", "exec": "ts-node" } 9 tscon fi g.json { "compilerOptions": { "target": "es5", "module": "commonjs", "lib": ["ES2020", "DOM"], "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true } }
  • 28. Babel Coder PRIMITIVE DATA TYPES • string • number • bigint • boolean • null • undefined • symbol
  • 29. Babel Coder PRIMITIVE DATA TYPES const num1: number = 10 const num2 = 20 const bool1: boolean = true const bool2 = false const str1: string = "hello" const str2 = "world"
  • 30. Babel Coder ANY AND UNKNOWN function next(num: number) { return num + 1; } let num: any = 10; num = 'hello'; next(num); num.toFixed(2); let num: unknown = 10; num = 'hello'; // Argument of type 'unknown' is not assignable to parameter of type 'number'. next(num); // Object is of type 'unknown'. num.toFixed(2); const num: unknown = 10; next(num); if (typeof num === 'number') { next(num); }
  • 31. Babel Coder LITERAL TYPES let str1: 'Hello' = 'Hello'; let str2: string = str1; // Type 'string' is not assignable to type '"Hello"'. str1 = str2; let str1 = 'Hello'; // string const str2 = 'Hello'; // Hello function permission(role: 'Admin' | 'Moderator' | 'Editor') { // do sth } permission('Admin'); let role = 'Editor'; // Argument of type 'string' is not assignable // to parameter of type '"Admin" | "Moderator" | "Editor"'. permission(role); permission(role as 'Editor');
  • 32. Babel Coder ARRAY let nums1: number[] = [1, 2, 3] // number[] let nums2: Array<number> = [1, 2, 3] // number[] let nums3 = [1, 2, 3] // number[] const nums4 = [1, 2, 3] // number[] const nums5: readonly number[] = [1, 2, 3] // readonly number[] const nums6: ReadonlyArray<number> = [1, 2, 3] // readonly number[] const nums7 = nums6 as number[]; // number[] const foo: string[] = []; // OK const a: never[] = []; // OK const b: never[] = [1, 2]; // Type 'number' is not assignable to type 'never'
  • 33. Babel Coder ENUM enum Role { Admin, Moderator, Editor, } const myRole: Role = Role.Admin; // 0 Role[0]; // Admin Role.Admin // 0 enum Role { Admin, Moderator, Editor, } enum Role { Admin = 'Admin', Moderator = 'Moderator', Editor = 'Editor', } Role.Admin; // Admin
  • 34. Babel Coder INTERFACES let person; // any person = { name: 'Somchai', age: 24, gender: 'male', }; interface Person { name: string; age: number; gender: string; } let person: Person; person = { name: 'Somchai', age: 24, gender: 'male', }; // Property 'gender' is missing in type // ‘{ name: string; age: number; }' // but required in type 'Person'. const person: Person = { name: 'Somchai', age: 24, }; const person: Person = { name: 'Somchai', age: 24, gender: 'male', };
  • 35. Babel Coder EXTENDING INTERFACES interface Website { url: string; } interface Article { title: string; content: string; } interface BlogPost extends Website, Article { view: number; } const post: BlogPost = { url: 'https://www.babelcoder.com/blog/articles/typescript-classes', title: 'การใ ช้ งานคลาสใน TypeScript', content: '...', view: 999, };
  • 36. Babel Coder READONLY AND OPTIONAL PROPERTIES interface Person { fi rstName: string; lastName: string; middleName?: string; readonly gender: 'Male' | 'Female'; } let somchai: Person = { fi rstName: 'Somchai', lastName: 'Haha', gender: 'Male', }; // Cannot assign to 'gender' because // it is a read-only property. somchai.gender = 'Female';
  • 37. Babel Coder TYPE ALIAS interface Person { name: string; age: number; gender: string; } type Person = { name: string; age: number; gender: string; }; interface Website { url: string; } interface Article { title: string; content: string; } interface BlogPost extends Website, Article { view: number; } type Website = { url: string; }; type Article = { title: string; content: string; }; type BlogPost = Website & Article & { view: number; };
  • 38. Babel Coder FUNCTION TYPES function getFullName( fi rstName, lastName) { return `${ fi rstName} ${lastName}`; } function getFullName( fi rstName: string, lastName: string): string { return `${ fi rstName} ${lastName}`; } const getFullName = function ( fi rstName: string, lastName: string): string { return `${ fi rstName} ${lastName}`; };
  • 39. Babel Coder FUNCTION TYPES const getFullName = ( fi rstName, lastName) => { return `${ fi rstName} ${lastName}`; }; const getFullName = ( fi rstName: string, lastName: string): string => { return `${ fi rstName} ${lastName}`; }; type GetFullNameFn = ( fi rstName: string, lastName: string) => string; const getFullName: GetFullNameFn = ( fi rstName, lastName) => { return `${ fi rstName} ${lastName}`; };
  • 40. Babel Coder CONST ASSERTIONS // const theme: { // colors: { // amethyst: "#9b59b6"; // carrot: string; // }; // } const theme = { colors: { amethyst: '#9b59b6' as const, carrot: '#e67e22', }, }; // const theme: { // colors: { // amethyst: string; // carrot: string; // }; // } const theme = { colors: { amethyst: '#9b59b6', carrot: '#e67e22', }, }; // const theme: { // readonly colors: { // readonly amethyst: "#9b59b6"; // readonly carrot: "#e67e22"; // }; // } const theme = { colors: { amethyst: '#9b59b6', carrot: '#e67e22', }, } as const;
  • 41. Babel Coder TYPEOF const user = { name: 'Somchai' }; console.log(typeof user); // 'object' // type User = { // name: string; // } type User = typeof user;
  • 42. Babel Coder UNION TYPES type Printable = string | string[]; const text: Printable = 'my message'; function format(thing: Printable): string { if (Array.isArray(thing)) return thing.join(', '); return thing; }
  • 43. Babel Coder INTERSECTION TYPES interface Identity { id: number; name: string; } interface Contact { email: string; phone: string; address: string; } type Employee = Identity & Contact; const somchai: Employee = { id: 11001, name: 'Somchai', email: 'somchai@haha.com', phone: '082-111-1111', address: '111/11', };
  • 44. Babel Coder CLASSES class BankAccount { static interestRate = 3.5; balance: number; constructor(balance: number) { this.balance = balance; } getInterest() { return this.balance * BankAccount.interestRate; } } const myAcc1 = new BankAccount(20); const myAcc2 = new BankAccount(30); myAcc1.balance; // 20 myAcc1.getInterest(); // 70 myAcc1 balance: 20 getInterest myAcc2 balance: 30 getInterest getInterest 3.5 BankAccount
  • 45. Babel Coder ACCESS MODIFIERS class BankAccount { protected balance: number; constructor(balance: number) { this.balance = balance; } withdraw(amount: number) { if (amount <= this.balance) this.balance -= amount; } deposit(amount: number) { if (amount > 0) this.balance += amount; } } class SavingAccount extends BankAccount { static readonly interestRate = 3.5; private readonly debitCard: number; constructor(balance: number, debitCard: number) { super(balance); this.debitCard = debitCard; } getInterest() { return this.balance * SavingAccount.interestRate; } }
  • 46. Babel Coder PARAMETER PROPERTIES class BankAccount { constructor(protected balance: number) {} withdraw(amount: number) { if (amount <= this.balance) this.balance -= amount; } deposit(amount: number) { if (amount > 0) this.balance += amount; } } class SavingAccount extends BankAccount { static interestRate = 3.5; constructor( balance: number, private readonly debitCard: number) { super(balance); } getInterest() { return this.balance * SavingAccount.interestRate; } }
  • 47. Babel Coder KEYWORD NEW class Person { constructor() {} } function get<T>(ctor: Factory<T>) { return new ctor(); } // const person: Person const person = get(Person); interface Factory<T> { new (...args: any[]): T; } // OR type Factory<T> = new (...args: any[]) => T;
  • 48. Babel Coder GENERIC FUNCTIONS function lastNum(arr: number[], count: number) { return arr.slice(arr.length - count); } lastNum([1, 2, 3, 4, 5], 3); // [3, 4, 5] function lastStr(arr: string[], count: number) { return arr.slice(arr.length - count); } lastStr(['A', 'B', 'C', 'D', 'E'], 2); // ['D', 'E'] function last<T>(arr: T[], count: number) { return arr.slice(arr.length - count); } const last = <T>(arr: T[], count: number) => { return arr.slice(arr.length - count); }; last<string>(['A', 'B', 'C', 'D', 'E'], 2); last(['A', 'B', 'C', 'D', 'E'], 2);
  • 49. Babel Coder GENERIC TYPES AND INTERFACES const head = <T>(arr: T[]) => arr[0]; const tail = <T>(arr: T[]) => arr[arr.length - 1]; type GetItem<T> = (arr: T[]) => T; interface GetItem<T> { (arr: T[]): T; } const option: GetItem<number> = head; option([1, 2, 3]); function getItem<T>(list: T[], fn: GetItem<T>): T { return fn(list); } getItem([1, 2, 3], head); // 1 getItem([1, 2, 3], tail); // 3
  • 51. Babel Coder RECORD type MyRecord<T extends string | number | symbol, U> = { [K in T]: U; }; type keys = 'name' | 'address'; // type MyPerson = { // name: string; // address: string; // } type MyPerson = MyRecord<keys, string>; type Person = Record<keys, string>;
  • 52. Babel Coder PICK AND OMIT type MyPick<T, K extends keyof T> = { [P in K]: T[P]; }; type Person = { name: string; age: number; address: string; }; // type NameAndAge = { // name: string; // age: number; // } type MyNameAndAge = MyPick<Person, 'name' | 'age'>; type NameAndAge = Pick<Person, 'name' | 'age'>; type MyOmit<T, K extends string | number | symbol> = Pick< T, Exclude<keyof T, K> >; type Person = { name: string; age: number; address: string; }; // type MyAddress = { // address: string; // } type MyAddress = MyOmit<Person, 'name' | 'age'>; type Address = Omit<Person, 'name' | 'age'>;
  • 53. Babel Coder REQUIRED AND PARTIAL type MyPartial<T> = { [K in keyof T]?: T[K]; }; type Person = { name: string; age: number; address: string; }; // type MyPartialPerson = { // name?: string | unde fi ned; // age?: number | unde fi ned; // address?: string | unde fi ned; // } type MyPartialPerson = MyPartial<Person>; type PartialPerson = Partial<Person>; type MyRequired<T> = { [K in keyof T]-?: T[K]; }; type Person = { name: string; age: number; address: string; }; // type MyRequiredPerson = { // name: string; // age: number; // address: string; // } type MyRequiredPerson = MyRequired<Person>; type RequiredPerson = Required<Person>;
  • 54. Babel Coder READONLY type MyReadonly<T> = { readonly [K in keyof T]: T[K]; }; type Person = { name: string; age: number; address: string; }; // type MyReadOnlyPerson = { // readonly name: string; // readonly age: number; // readonly address: string; // } type MyReadOnlyPerson = MyReadonly<Person>; type ReadOnlyPerson = Readonly<Person>;
  • 56. Babel Coder DEFINITELY TYPED // Could not fi nd a declaration fi le for module 'lodash'. import lodash from 'lodash'; yarn add @types/lodash yarn add @types/absinthe__socket