50 สิ่งที่ต้องรู้เกี่ยวกับ TypeScript JavaScript ที่เพิ่ม Static Type Checking ขึ้นมา ช่วยจับ bug
50 สิ่งที่ต้องรู้เกี่ยวกับ TypeScript
TypeScript คือ JavaScript ที่เพิ่ม Static Type Checking ขึ้นมา ช่วยจับ bug ตั้งแต่ตอน compile ไม่ต้องรอถึง runtime
⸻
พื้นฐาน
1. ถูกสร้างโดย Microsoft ปี 2012
Anders Hejlsberg (ผู้สร้าง C# และ Delphi) เป็นผู้ออกแบบ TypeScript
2. TypeScript คือ Superset ของ JavaScript
JavaScript ที่ถูกต้องทุกตัว คือ TypeScript ที่ถูกต้อง — รันไฟล์ .js ได้เลย
3. Compile เป็น JavaScript
TypeScript ไม่รันตรงๆ — tsc แปลงเป็น .js ก่อน run
tsc app.ts # สร้าง app.js
4. Type Erasure
ตอน compile จะถอด type ทิ้ง — runtime คือ JavaScript ปกติ
5. เหตุผลที่นิยม
* จับ bug ตั้งแต่เขียน
* IDE autocomplete ดีขึ้น
* Refactor ง่ายขึ้น
* ทีมใหญ่ทำงานร่วมกันได้ดีขึ้น
⸻
Basic Types
6. Type Annotations
let name: string = “John”;
let age: number = 30;
let isActive: boolean = true;
let items: string[] = [“a”, “b”];
let tuple: [string, number] = [“age”, 30];
7. Type Inference
TypeScript เดา type ได้เอง — ไม่ต้องเขียนขึ้นหมด
let name = “John”; // type: string (เดาอัตโนมัติ)
8. Union Types
let id: string | number;
id = “abc”; // OK
id = 123; // OK
id = true; // Error!
9. Literal Types
let direction: “north” | “south” | “east” | “west”;
direction = “north”; // OK
direction = “up”; // Error!
10. any, unknown, never, void
* any: ปิด type checking (หลีกเลี่ยง!)
* unknown: ต้องเช็ค type ก่อนใช้
* never: function ไม่มีวัน return
* void: function ไม่ return ค่า
⸻
Interfaces & Types
11. Interface
interface User {
id: number;
name: string;
email?: string;
readonly createdAt: Date;
}
const user: User = {
id: 1,
name: “John”,
createdAt: new Date()
};
12. Type Aliases
type Point = { x: number; y: number };
type ID = string | number;
type Callback = (data: string) => void;
13. Interface vs Type
Interface: ขยาย ได้ (declaration merging), เหมาะ OOP
Type: flexible กว่า, ทำ union/intersection ได้
14. Extending Interfaces
interface Animal { name: string; }
interface Dog extends Animal {
bark(): void;
}
15. Intersection Types
type Employee = User & { salary: number };
⸻
Functions
16. Function Types
function add(a: number, b: number): number {
return a + b;
}
const multiply: (a: number, b: number) => number =
(a, b) => a * b;
17. Optional & Default Parameters
function greet(
name: string,
greeting: string = “Hello”
): string {
return ${greeting}, ${name};
}
function log(message: string, level?: string) {
}
18. Rest Parameters
function sum(…nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
19. Function Overloading
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
return typeof value === ‘string’
? value.toUpperCase()
: value.toFixed(2);
}
20. Arrow Functions
const greet = (name: string): string =>
Hello, ${name};
⸻
Generics
21. Generic Functions
function identity(arg: T): T {
return arg;
}
const num = identity(42);
const str = identity(“hello”);
22. Generic Constraints
function longest<T extends { length: number }>(
a: T,
b: T
): T {
return a.length > b.length ? a : b;
}
23. Generic Interfaces
interface ApiResponse {
data: T;
status: number;
message: string;
}
const userResponse: ApiResponse =
await fetchUser();
24. Generic Classes
class Stack {
private items: T[] = [];
push(item: T) {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
}
const numStack = new Stack();
25. Default Generic Type
interface Config<T = string> {
value: T;
}
⸻
Advanced Types
26. Utility Types: Partial
interface User {
id: number;
name: string;
email: string;
}
type UserUpdate = Partial;
27. Pick<T, K> และ Omit<T, K>
type UserPreview = Pick<User, ‘id’ | ‘name’>;
type UserWithoutId = Omit<User, ‘id’>;
28. Required และ Readonly
type RequiredUser = Required;
type ReadonlyUser = Readonly;
29. Record<K, T>
type Roles = ‘admin’ | ‘user’ | ‘guest’;
type Permissions = Record<Roles, string[]>;
30. Mapped Types
type Optional = {
[K in keyof T]?: T[K];
};
⸻
Type Guards
31. typeof Guards
function format(value: string | number) {
if (typeof value === ‘string’) {
return value.toUpperCase();
}
return value.toFixed(2);
}
32. instanceof Guards
if (error instanceof TypeError) {
console.log(error.message);
}
33. in Operator
if (‘email’ in user) {
console.log(user.email);
}
34. Type Predicates
function isString(value: unknown): value is string {
return typeof value === ‘string’;
}
if (isString(data)) {
console.log(data.toUpperCase());
}
35. Discriminated Unions
type Shape =
| { kind: ‘circle’; radius: number }
| { kind: ‘square’; side: number };
function area(shape: Shape) {
switch (shape.kind) {
case ‘circle’:
return Math.PI * shape.radius ** 2;
case 'square':
return shape.side ** 2;
}
}
⸻
Classes
36. Classes พร้อม Access Modifiers
class User {
public name: string;
private password: string;
protected role: string;
constructor(name: string, password: string) {
this.name = name;
this.password = password;
this.role = ‘user’;
}
}
37. Shorthand Constructor
class User {
constructor(
public name: string,
private password: string,
public readonly id: number
) {}
}
38. Abstract Classes
abstract class Animal {
abstract makeSound(): void;
move() {
console.log(“moving…”);
}
}
class Dog extends Animal {
makeSound() {
console.log(“woof!”);
}
}
39. Implements Interface
interface Comparable {
compareTo(other: T): number;
}
class Score implements Comparable {
constructor(public value: number) {}
compareTo(other: Score) {
return this.value - other.value;
}
}
⸻
Configuration
40. tsconfig.json
{
“compilerOptions”: {
“target”: “ES2022”,
“module”: “ESNext”,
“strict”: true,
“esModuleInterop”: true,
“skipLibCheck”: true,
“outDir”: “./dist”
}
}
41. strict Mode
เปิด "strict": true ใน tsconfig — เปิดทุกการตรวจสอบเข้มงวด แนะนำสำหรับโปรเจกต์ใหม่!
42. strictNullChecks
let name: string = null; // Error
let name: string | null = null; // OK
⸻
Modules
43. import/export
// utils.ts
export const add =
(a: number, b: number) => a + b;
export default class Calculator { }
// main.ts
import Calculator, { add } from ‘./utils’;
import type { User } from ‘./types’;
⸻
Best Practices
44. หลีกเลี่ยง any
// ผิด
function process(data: any) { }
// ถูก
function process(data: T) { }
45. Use as const
const colors = [‘red’, ‘green’, ‘blue’] as const;
46. Template Literal Types
type Greeting = Hello, ${string};
type Direction =
${'top' | 'bottom'}-${'left' | 'right'};
47. Enums (ระวัง!)
const Status = {
Active: ‘active’,
Inactive: ‘inactive’
} as const;
type Status =
typeof Status[keyof typeof Status];
⸻
เครื่องมือและ Ecosystem
48. ใช้กับ Frameworks
* React: type props ด้วย interface
* Next.js: support TypeScript out-of-box
* NestJS: backend framework สำหรับ TypeScript โดยเฉพาะ
* Vue 3: รองรับ TS เต็มที่
49. tsx vs ts
* .ts — TypeScript ปกติ
* .tsx — TypeScript + JSX (React)
50. @types Packages
npm install –save-dev @types/node @types/react
Library หลาย ๆ ตัวที่เขียนด้วย JavaScript จะมี type definitions ใน @types/*
⸻
สรุป: TypeScript กลายเป็นมาตรฐานของโปรเจกต์ใหญ่ๆ ในปัจจุบัน — Microsoft, Google, Airbnb ใช้กันหมด เริ่มจาก strict mode และค่อยๆ เรียนรู้ utility types เพื่อใช้ประโยชน์เต็มที่

















