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

Similar to js+ts fullstack typescript with react and express.pdf (20)

PDF
Introduction to ECMAScript 2015
Tomasz Dziuda
 
PDF
Modern Application Foundations: Underscore and Twitter Bootstrap
Howard Lewis Ship
 
PDF
Introduction to ES2015
kiranabburi
 
PDF
Essentials and Impactful Features of ES6
Riza Fahmi
 
ODP
ES6 PPT FOR 2016
Manoj Kumar
 
PDF
Static types on javascript?! Type checking approaches to ensure healthy appli...
Arthur Puthin
 
ODP
EcmaScript 6
Manoj Kumar
 
PDF
Explaining ES6: JavaScript History and What is to Come
Cory Forsyth
 
PDF
Es6 to es5
Shakhzod Tojiyev
 
PPTX
Ecmascript 6
Gatuk S. Chattanon
 
PDF
Intro to React
Troy Miles
 
PDF
Idiomatic Javascript (ES5 to ES2015+)
David Atchley
 
PDF
Reason - introduction to language and its ecosystem | Łukasz Strączyński
Grand Parade Poland
 
PDF
ECMAScript2015
qmmr
 
PDF
Introduction to Swift 2
Joris Timmerman
 
PDF
BabelJS - James Kyle at Modern Web UI
modernweb
 
PDF
Swift Programming
Codemotion
 
PDF
Swift Introduction
Giuseppe Arici
 
PPT
Intermediate JavaScript
☆ Milan Adamovsky ☆
 
PDF
TypeScript Introduction
Hans Höchtl
 
Introduction to ECMAScript 2015
Tomasz Dziuda
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Howard Lewis Ship
 
Introduction to ES2015
kiranabburi
 
Essentials and Impactful Features of ES6
Riza Fahmi
 
ES6 PPT FOR 2016
Manoj Kumar
 
Static types on javascript?! Type checking approaches to ensure healthy appli...
Arthur Puthin
 
EcmaScript 6
Manoj Kumar
 
Explaining ES6: JavaScript History and What is to Come
Cory Forsyth
 
Es6 to es5
Shakhzod Tojiyev
 
Ecmascript 6
Gatuk S. Chattanon
 
Intro to React
Troy Miles
 
Idiomatic Javascript (ES5 to ES2015+)
David Atchley
 
Reason - introduction to language and its ecosystem | Łukasz Strączyński
Grand Parade Poland
 
ECMAScript2015
qmmr
 
Introduction to Swift 2
Joris Timmerman
 
BabelJS - James Kyle at Modern Web UI
modernweb
 
Swift Programming
Codemotion
 
Swift Introduction
Giuseppe Arici
 
Intermediate JavaScript
☆ Milan Adamovsky ☆
 
TypeScript Introduction
Hans Höchtl
 

More from NuttavutThongjor1 (20)

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

Recently uploaded (20)

PPTX
From spreadsheets and delays to real-time control
SatishKumar2651
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
Ready Layer One: Intro to the Model Context Protocol
mmckenna1
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
Simplify React app login with asgardeo-sdk
vaibhav289687
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
PPTX
Function & Procedure: Function Vs Procedure in PL/SQL
Shani Tiwari
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
intro_to_cpp_namespace_robotics_corner.pdf
MohamedSaied877003
 
PPTX
Build a Custom Agent for Agentic Testing.pptx
klpathrudu
 
PDF
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
PDF
Best Web development company in india 2025
Greenusys
 
PDF
Dipole Tech Innovations – Global IT Solutions for Business Growth
dipoletechi3
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PPTX
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
From spreadsheets and delays to real-time control
SatishKumar2651
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Ready Layer One: Intro to the Model Context Protocol
mmckenna1
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
Simplify React app login with asgardeo-sdk
vaibhav289687
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Get Started with Maestro: Agent, Robot, and Human in Action – Session 5 of 5
klpathrudu
 
Function & Procedure: Function Vs Procedure in PL/SQL
Shani Tiwari
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
intro_to_cpp_namespace_robotics_corner.pdf
MohamedSaied877003
 
Build a Custom Agent for Agentic Testing.pptx
klpathrudu
 
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
Best Web development company in india 2025
Greenusys
 
Dipole Tech Innovations – Global IT Solutions for Business Growth
dipoletechi3
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Comprehensive Risk Assessment Module for Smarter Risk Management
EHA Soft Solutions
 
Ad

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: '[email protected]', 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