What is TypeScript?

TypeScript is a superset of JavaScript that adds static typing and additional features like interfaces, enums, and generics. It helps developers catch errors at compile time rather than runtime, making code more robust, scalable, and maintainable.

TypeScript code is compiled (or transpiled) to plain JavaScript, which runs in any browser or JavaScript environment.


TypeScript Data Types

TypeScript offers several built-in types:

  1. number — Numeric values
  2. string — Text values
  3. boolean — true or false
  4. any — Any type (opt-out of type checking)
  5. unknown — Similar to any, but safer
  6. void — No value (used in functions with no return)
  7. null — Null value
  8. undefined — Undefined value
  9. never — Represents values that never occur (like a function that always throws)
  10. object — Non-primitive values
  11. array — Collection of values (number[], string[])
  12. tuple — Fixed-length array with known types ([string, number])
  13. enum — Set of named constants
  14. union — Value can be more than one type (string | number)
  15. literal — Exact value ('success' | 'error')
  16. function — Type for functions

Example:

let id: number = 5;

Explanation:


Can we change a variable's type on the go in TypeScript?

No — TypeScript enforces static typing.

Once a variable is assigned a type, either implicitly or explicitly, it cannot be changed to another type.

Example:

let name = "Vivek";  // TypeScript infers this as type 'string'
name = "Vernekar";   // ✅ Allowed
name = 123;          // ❌ Error: Type 'number' is not assignable to type 'string'