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'
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)
}
}
Babel Coder
RECAP TYPESCRIPT
Babel Coder
TYPESCRIPT
ECMAScript
JavaScript
TypeScript
function plusOne(num: number) {
return num + 1;
}
Babel Coder
BASIC TYPES
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
NULL AND UNDEFINED
const a = null;
const b = unde
fi
ned;
let a = 'hello';
a = null;
a = unde
fi
ned;
console.log(a[0].toUpperCase() + a.slice(1));
Babel Coder
VOID
function greet(): void {
console.log('Hello World');
}
let x: void = unde
fi
ned;
// if `--strictNullChecks` is not given
x = null;
void is a little like the opposite of any: the absence of having any type at all.
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
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
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
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
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
GENERIC CONSTRAINTS
interface Account {
username: string;
}
interface Admin extends Account {
role: 'Admin' | 'Moderator';
}
interface User extends Account {
age: number;
}
function getUsername<T extends Account>(account: T) {
return account.username;
}
function getUsername(account: Account) {
return account.username;
}
Babel Coder
CONDITIONAL TYPES
T extends U ? X : Y
The type above means when T is assignable
to U the type is X, otherwise the type is Y.
A conditional type selects one of two possible types based on a condition expressed as a type
relationship test:
Babel Coder
RETURNTYPE
type MyReturnType<T extends (...args: any) => any> = T extends (
...args: any
) => infer R
? R
: any;
type Person = {
name: string;
age: number;
};
function get(person: Person, key: keyof Person) {
return person[key];
}
// type myGetReturnType = string | number
type myGetReturnType = MyReturnType<typeof get>;
type getReturnType = ReturnType<typeof get>;
Babel Coder
PARAMETERS
type MyParameters<T extends (...args: any) => any> = T extends (
...args: infer P
) => any
? P
: never;
type Person = {
name: string;
age: number;
};
function get(person: Person, key: keyof Person) {
return person[key];
}
// type myGetParams = [person: Person, key: "name" | "age"]
type MyGetParams = MyParameters<typeof get>;
type GetParams = Parameters<typeof get>;
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>;

More Related Content

PDF
recap-ts.pdf
PDF
fullstack typescript with react and express.pdf
PDF
js+ts fullstack typescript with react and express.pdf
PDF
recap-js.pdf
PDF
Back to the Future with TypeScript
PPTX
Academy PRO: ES2015
PPTX
Type Driven Development with TypeScript
recap-ts.pdf
fullstack typescript with react and express.pdf
js+ts fullstack typescript with react and express.pdf
recap-js.pdf
Back to the Future with TypeScript
Academy PRO: ES2015
Type Driven Development with TypeScript

Similar to recap-js-and-ts.pdf (20)

KEY
Introduction to Groovy
PDF
ECMAScript 6
PPTX
Howard type script
PPTX
TypeScript by Howard
PPTX
Type script by Howard
PPTX
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
PDF
Game Design and Development Workshop Day 1
PDF
ECMAScript 6 and beyond
PPTX
Introduction to TypeScript
PPTX
ES6: Features + Rails
PDF
JavaScript - Agora nervoso
PDF
javascript for modern application.pdf
PPTX
KotlinForJavaDevelopers-UJUG.pptx
PPTX
Groovy grails types, operators, objects
PDF
TypeScript Introduction
PDF
JavaScript for PHP developers
PDF
Idiomatic Javascript (ES5 to ES2015+)
PDF
JavaScript - new features in ECMAScript 6
PDF
Implicit parameters, when to use them (or not)!
PDF
cypress.pdf
Introduction to Groovy
ECMAScript 6
Howard type script
TypeScript by Howard
Type script by Howard
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
Game Design and Development Workshop Day 1
ECMAScript 6 and beyond
Introduction to TypeScript
ES6: Features + Rails
JavaScript - Agora nervoso
javascript for modern application.pdf
KotlinForJavaDevelopers-UJUG.pptx
Groovy grails types, operators, objects
TypeScript Introduction
JavaScript for PHP developers
Idiomatic Javascript (ES5 to ES2015+)
JavaScript - new features in ECMAScript 6
Implicit parameters, when to use them (or not)!
cypress.pdf

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

Recently uploaded (20)

PDF
Literature_Review_methods_ BRACU_MKT426 course material
PDF
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
PPTX
Education and Perspectives of Education.pptx
PPTX
Climate Change and Its Global Impact.pptx
PDF
LIFE & LIVING TRILOGY- PART (1) WHO ARE WE.pdf
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
HVAC Specification 2024 according to central public works department
PDF
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
PPTX
B.Sc. DS Unit 2 Software Engineering.pptx
PPTX
DRUGS USED FOR HORMONAL DISORDER, SUPPLIMENTATION, CONTRACEPTION, & MEDICAL T...
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PDF
CRP102_SAGALASSOS_Final_Projects_2025.pdf
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
PDF
LIFE & LIVING TRILOGY - PART - (2) THE PURPOSE OF LIFE.pdf
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PDF
English Textual Question & Ans (12th Class).pdf
PDF
Race Reva University – Shaping Future Leaders in Artificial Intelligence
Literature_Review_methods_ BRACU_MKT426 course material
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
Education and Perspectives of Education.pptx
Climate Change and Its Global Impact.pptx
LIFE & LIVING TRILOGY- PART (1) WHO ARE WE.pdf
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
HVAC Specification 2024 according to central public works department
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
B.Sc. DS Unit 2 Software Engineering.pptx
DRUGS USED FOR HORMONAL DISORDER, SUPPLIMENTATION, CONTRACEPTION, & MEDICAL T...
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
Environmental Education MCQ BD2EE - Share Source.pdf
CRP102_SAGALASSOS_Final_Projects_2025.pdf
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
LIFE & LIVING TRILOGY - PART - (2) THE PURPOSE OF LIFE.pdf
Share_Module_2_Power_conflict_and_negotiation.pptx
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
English Textual Question & Ans (12th Class).pdf
Race Reva University – Shaping Future Leaders in Artificial Intelligence

recap-js-and-ts.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. 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. Babel Coder PRIMITIVE DATA TYPES • string • number • bigint • boolean • null • undefined • symbol
  • 18. 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"
  • 19. Babel Coder NULL AND UNDEFINED const a = null; const b = unde fi ned; let a = 'hello'; a = null; a = unde fi ned; console.log(a[0].toUpperCase() + a.slice(1));
  • 20. Babel Coder VOID function greet(): void { console.log('Hello World'); } let x: void = unde fi ned; // if `--strictNullChecks` is not given x = null; void is a little like the opposite of any: the absence of having any type at all.
  • 21. 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');
  • 22. 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'
  • 23. 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', };
  • 24. 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, };
  • 25. 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; };
  • 26. 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}`; };
  • 27. 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}`; };
  • 28. Babel Coder TYPEOF const user = { name: 'Somchai' }; console.log(typeof user); // 'object' // type User = { // name: string; // } type User = typeof user;
  • 29. 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; }
  • 30. 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', };
  • 31. 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);
  • 32. 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
  • 33. Babel Coder GENERIC CONSTRAINTS interface Account { username: string; } interface Admin extends Account { role: 'Admin' | 'Moderator'; } interface User extends Account { age: number; } function getUsername<T extends Account>(account: T) { return account.username; } function getUsername(account: Account) { return account.username; }
  • 34. Babel Coder CONDITIONAL TYPES T extends U ? X : Y The type above means when T is assignable to U the type is X, otherwise the type is Y. A conditional type selects one of two possible types based on a condition expressed as a type relationship test:
  • 35. Babel Coder RETURNTYPE type MyReturnType<T extends (...args: any) => any> = T extends ( ...args: any ) => infer R ? R : any; type Person = { name: string; age: number; }; function get(person: Person, key: keyof Person) { return person[key]; } // type myGetReturnType = string | number type myGetReturnType = MyReturnType<typeof get>; type getReturnType = ReturnType<typeof get>;
  • 36. Babel Coder PARAMETERS type MyParameters<T extends (...args: any) => any> = T extends ( ...args: infer P ) => any ? P : never; type Person = { name: string; age: number; }; function get(person: Person, key: keyof Person) { return person[key]; } // type myGetParams = [person: Person, key: "name" | "age"] type MyGetParams = MyParameters<typeof get>; type GetParams = Parameters<typeof get>;
  • 37. 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'>;
  • 38. 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>;