ตัวแปร JavaScript ไม่มีชนิด (no types) แต่ ค่ามีชนิด วิธีประกาศตัวแปร:
var rank = 5; var name = "John";
คุณยังเขียนได้แบบนี้:
var rank = 5; rank = 'first'; document.write(rank);
เห็นได้ว่า ไม่ได้ประโยชน์อะไรที่จะระบุชนิดในการประกาศตัวแปร เพราะชนิดข้อมูลถูกกำหนดโดยค่าของตัวแปร
ความเข้าใจที่ถูกต้อง
JavaScript เป็น Dynamically Typed — ตัวแปรเป็นเพียง "ช่องเก็บ" (container) ค่าที่อยู่ภายในจึงมีชนิด (type) และสามารถเปลี่ยนชนิดได้ตลอดเวลา
TypeScript: Static Typing สำหรับ JavaScript
หากต้องการ static typing ใช้ TypeScript (superset ของ JavaScript):
// TypeScript
let rank: number = 5;
rank = "first"; // Error: Type 'string' is not assignable to type 'number'
let name: string = "John";
const PI: number = 3.14159;
let user: { name: string; age: number } = { name: "John", age: 30 };
TypeScript compile เป็น JavaScript ธรรมดา รันได้ทุกที่ที่ JS รันได้