Understanding TypeScript Fundamentals: Types, Installation, and Key Differences from JavaScript
TypeScript and JavaScript represent distinct language paradigms. TypeScript is a strongly typed language, whereas JavaScript is weakly typed. Strongly typed languages can support both static and dynamic typing models, while weakly typed languages primarily support dynamic typing.
Strongly Typed vs. Weakly Typed Languages
- Strongly Typed Languages: These languages enforce strict data type rules. A variable's data type cannot be changed unlesss an explicit type conversion (casting) is performed.
- Weakly Typed Languages: In contrast, these languages allow variables to be assigned values of different data types without explicit conversion. Examples include PHP, Ruby, and Python.
Static vs. Dynamic Languages
- Static Languages: Variable data types are determined at compile time, and the program's structure cannot be altered during execution. Examples are C++, Java, and C#.
- Dynamic Languages: Data types and structures are resolved at runtime. Variables do not require type declarations before use. JavaScript, PHP, Ruby, and Python fall in to this category.
Distinguishing TypeScript from JavaScript
Before diving into TypeScript, it's crucial to understand how it differs from JavaScript. The following table outlines the key distinctions:
| TypeScript | JavaScript |
|---|---|
| Strongly typed, supporting both static and dynamic typing. | Weakly typed, supporting dynamic typing. |
| Designed to manage complexity in large-scale applications. | A scripting language primarily for creating dynamic web content. |
| Errors can be identified and fixed during compilation. | Errors are only discovered at runtime. |
| Must be transpiled to JavaScript before execution in a browser. | Can be executed directly by browsers. |
| Supports modules, generics, and interfaces. | Lacks native support for modules, generics, and interfaces. |
Installing TypeScript
-
Installation Use npm or Yarn to install TypeScript globally:
npm install -g typescript # or yarn global add typescript -
Check Version Verify the installation by checking the compiler version:
tsc --version -
Compile a TypeScript File The TypeScript compiler (
tsc) converts.tsfiles into.jsfiles:tsc filename.ts
TypeScript Data Types
TypeScript extends the data types available in ES6 (Boolean, Number, String, Array, Function, Object, Symbol, undefined, null) with several additional types:
voidanyneverunknown- Tuple
- Enum (
enum) - Various advanced types