SlideShare une entreprise Scribd logo
1  sur  56
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

Contenu connexe

Similaire à js+ts fullstack typescript with react and express.pdf

JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
qmmr
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 

Similaire à js+ts fullstack typescript with react and express.pdf (20)

cypress.pdf
cypress.pdfcypress.pdf
cypress.pdf
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Intro to Ember.JS 2016
Intro to Ember.JS 2016Intro to Ember.JS 2016
Intro to Ember.JS 2016
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
javascript for modern application.pdf
javascript for modern application.pdfjavascript for modern application.pdf
javascript for modern application.pdf
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Javascript the New Parts v2
Javascript the New Parts v2Javascript the New Parts v2
Javascript the New Parts v2
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
 
Js hacks
Js hacksJs hacks
Js hacks
 
Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScript
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Latinoware
LatinowareLatinoware
Latinoware
 

Plus de NuttavutThongjor1

8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
NuttavutThongjor1
 
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
NuttavutThongjor1
 
mean stack mean stack mean stack mean stack
mean stack mean stack  mean stack  mean stackmean stack mean stack  mean stack  mean stack
mean stack mean stack mean stack mean stack
NuttavutThongjor1
 

Plus de NuttavutThongjor1 (20)

Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
Intro to Modern DevOps.pdfIntro to Modern DevOps.pdfIntro to Modern DevOps.pdf
 
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
10 วัฒนธรรมองค์กรของ DevOps.pdf10 วัฒนธรรมองค์กรของ DevOps.pdf
 
9 logging and monitoring.pdf 9 logging and monitoring.pdf
9 logging and monitoring.pdf 9 logging and monitoring.pdf9 logging and monitoring.pdf 9 logging and monitoring.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
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
8 iac.pdf 8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf8 iac.pdf
 
7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf
7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf
7 cicd.pdf 7 cicd.pdf 7 cicd.pdf 7 cicd.pdf
 
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf 6 GitOps คืออะไร.pdf
 
5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf
5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf
5 Kubernetes.pdf 5 Kubernetes.pdf 5 Kubernetes.pdf
 
4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf
4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf
4 Docker.pdf 4 Docker.pdf 4 Docker.pdf 4 Docker.pdf
 
3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf
3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf
3 Microservices.pdf 3 Microservices 3 Microservices.pdf.pdf
 
2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf
2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf
2 เทคโนโลยี cloud computing.pdf 2 เทคโนโลยี cloud computing.pdf
 
1 devops คืออะไร.pdf 1 devops คืออะไร.pdf
1 devops คืออะไร.pdf 1 devops คืออะไร.pdf1 devops คืออะไร.pdf 1 devops คืออะไร.pdf
1 devops คืออะไร.pdf 1 devops คืออะไร.pdf
 
angular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdfangular fundamentals.pdf angular fundamentals.pdf
angular fundamentals.pdf angular fundamentals.pdf
 
mean stack mean stack mean stack mean stack
mean stack mean stack  mean stack  mean stackmean stack mean stack  mean stack  mean stack
mean stack mean stack mean stack mean stack
 
pinia.pdf
pinia.pdfpinia.pdf
pinia.pdf
 
nuxt-rendering-modes.pdf
nuxt-rendering-modes.pdfnuxt-rendering-modes.pdf
nuxt-rendering-modes.pdf
 
zustand.pdf
zustand.pdfzustand.pdf
zustand.pdf
 
tanstack-query.pdf
tanstack-query.pdftanstack-query.pdf
tanstack-query.pdf
 
nuxt-fundamentals.pdf
nuxt-fundamentals.pdfnuxt-fundamentals.pdf
nuxt-fundamentals.pdf
 
vue-components.pdf
vue-components.pdfvue-components.pdf
vue-components.pdf
 
vue-reactivity.pdf
vue-reactivity.pdfvue-reactivity.pdf
vue-reactivity.pdf
 

Dernier

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Dernier (20)

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

js+ts fullstack typescript with react and express.pdf

  • 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