Primitive Types in TypeScript
Primitive Types in TypeScript
Section titled “Primitive Types in TypeScript”The string Type
Section titled “The string Type”let name: string = "Alice";let greeting: string = `Hello, ${name}!`;let multiLine: string = ` Line 1 Line 2`;
// Template literal typestype EventName = `on${Capitalize<string>}`;// "onChange" | "onClick" | "onSubmit" | ...
type Color = "red" | "green" | "blue";type ColorHex = `#${string}`;The number Type
Section titled “The number Type”let decimal: number = 42;let hex: number = 0xFF; // 255let binary: number = 0b1010; // 10let octal: number = 0o744; // 484let float: number = 3.14;let negative: number = -273;
// BigInt for large integerslet big: bigint = 9007199254740991n;let anotherBig = BigInt("9999999999999999");The boolean Type
Section titled “The boolean Type”let isActive: boolean = true;let isComplete: boolean = false;
// Boolean type guardsfunction processFlag(flag: boolean): string { if (flag) return "enabled"; return "disabled";}Common Mistakes
Section titled “Common Mistakes”| Mistake | Fix |
|---|---|
Using String instead of string | Use lowercase primitive types |
Forgetting BigInt suffix n | Add n suffix for BigInt literals |
Implicit any from missing annotation | Enable strict: true in tsconfig |
Interview Questions
Section titled “Interview Questions”Easy: What are the primitive types in TypeScript?
Medium: How do template literal types work with string literals?
Hard: When would you use bigint over number?