I. What Are JavaScript and TypeScript?
JavaScript (JS) is a dynamically typed programming language widely used in web front-end, server-side, and cross-platform development. It can run directly in the browser, or execute server-side programs with the help of runtimes such as Node.js, Deno, and Bun.
TypeScript (TS) is an open-source programming language developed and maintained by Microsoft. It is a superset of JavaScript, adding a static type system, interfaces, type aliases, generics, and other capabilities on top of JavaScript syntax.
The core design goal of TypeScript is not to create an entirely new runtime, but to provide more comprehensive static analysis capabilities on top of JavaScript.
1. Features of JavaScript
- Dynamic typing: Variables can hold data of different types during runtime.
- High flexibility: No need to declare variable types in advance.
- Direct execution: Browsers and JavaScript runtimes can execute JavaScript directly.
- Mature ecosystem: A rich set of frameworks, libraries, and development tools.
- Runtime type checking: Many type errors are only exposed when execution reaches the relevant code.
Example:
let value = 100;
value = "Hello";
value = true;
console.log(value);
JavaScript allows a variable to hold data of different types at different times.
2. Features of TypeScript
- Static type checking: A large number of type errors can be found at the compilation stage.
- Type inference: Types can be inferred from a variable's initial value and context.
- Interfaces and type aliases: Support for describing object structures and complex type relationships.
- Generic support: The ability to build reusable components with type constraints.
- JavaScript compatibility: Existing JavaScript code can usually be migrated to TypeScript incrementally.
Example:
let value: number = 100;
value = 200;
// 编译阶段报错
// value = "Hello";
TypeScript can detect assignment type mismatches during development and build stages.
II. Core Differences Between JavaScript and TypeScript
The biggest difference between the two lies in the type system and the checking capabilities during development, not in the execution mechanism of the final runtime.
| Comparison Dimension | JavaScript | TypeScript |
|---|---|---|
| Language positioning | Dynamically typed language | A JavaScript superset with a static type system |
| Type declarations | Usually not required | Supports explicit declarations |
| Type checking | Mainly occurs at runtime | Mainly occurs at the compilation or static checking stage |
| Type inference | Value types are determined at runtime | Static types are inferred during development |
| Interfaces | No native TypeScript-style interfaces | Supports interface |
| Type aliases | No support for static type aliases | Supports type |
| Generics | No static generic system | Supports generics |
| Compilation process | Usually executed directly, but can also go through a build | Usually requires transpilation or handling by a toolchain |
| Runtime environment | Browsers, Node.js, etc. | The runtime environment for compiled JavaScript |
| Developer experience | Flexible, with fewer type constraints | Stronger type hints, refactoring, and static analysis capabilities |
| Learning cost | Relatively low | Requires understanding the type system |
| Typical applications | Scripts, small projects, web applications | Medium-to-large projects, complex business systems, team collaboration |
Note: TypeScript does not automatically replace JavaScript at runtime. In the vast majority of cases, TypeScript source code is ultimately converted to JavaScript and then handed to a JavaScript runtime for execution.
III. Differences in the Type System
The type system is the most important difference between JavaScript and TypeScript.
1. JavaScript: Dynamic Typing
JavaScript uses a dynamic typing mechanism.
Variables themselves have no fixed static type constraints; only concrete values have corresponding types at runtime.
let data = 100;
console.log(typeof data); // number
data = "Hello";
console.log(typeof data); // string
data = {
name: "Alice"
};
console.log(typeof data); // object
JavaScript does not require a type to be specified when declaring a variable.
This approach brings high flexibility, but it also means that certain errors can only be discovered during runtime.
For example:
function calculateTotal(price, quantity) {
return price * quantity;
}
console.log(calculateTotal(100, 3)); // 300
console.log(calculateTotal("100", 3)); // 300
console.log(calculateTotal("Hello", 3)); // NaN
JavaScript's multiplication operation attempts numeric conversion.
If the input cannot be converted to a valid number, the result may be NaN, rather than directly reporting an error during development.
2. TypeScript: Static Type Checking
TypeScript adds a static type system on top of JavaScript.
Developers can explicitly declare types, or let the compiler infer types automatically.
function calculateTotal(
price: number,
quantity: number
): number {
return price * quantity;
}
console.log(calculateTotal(100, 3));
// Type error
// calculateTotal("100", 3);
Here:
price: numbermeans the price parameter must conform to thenumbertype.quantity: numbermeans the quantity parameter must conform to thenumbertype.: numbermeans the static type of the function's return value isnumber.
When a string is passed in, the TypeScript type checker reports an error.
3. Type Inference
TypeScript does not require all variables to explicitly declare types.
It can infer variable types based on their initial values.
let age = 25;
// Inferred as number
age = 30;
// Type error
// age = "Twenty";
Types can also be inferred from function return values:
function add(a: number, b: number) {
return a + b;
}
// Return type inferred as number
const result = add(10, 20);
Type inference can reduce repetitive declarations and keep code concise.
However, note that type inference is a static analysis capability at compile time; it does not mean that JavaScript at runtime gains TypeScript type information.
4. Type Erasure
TypeScript's type information is mainly used for static checking during development.
During conventional TypeScript transpilation, type declarations are removed and are not retained as part of JavaScript's runtime type system.
For example:
interface User {
id: number;
name: string;
}
function getUser(user: User): string {
return user.name;
}
const user: User = {
id: 1,
name: "Alice"
};
console.log(getUser(user));
After transpilation, the core JavaScript code is similar to:
function getUser(user) {
return user.name;
}
const user = {
id: 1,
name: "Alice"
};
console.log(getUser(user));
interface, parameter types, and return value types do not appear in the final JavaScript code.
This means the TypeScript type system generally cannot directly validate external data at runtime.
For example, for JSON data obtained from an HTTP endpoint, even if the developer has declared a TypeScript type, it cannot be guaranteed that the actual data conforms to that type.
IV. Differences Between Interfaces and Type Definitions
JavaScript itself does not have TypeScript's static interfaces and type alias mechanisms.
TypeScript can describe data structures through interface and type.
1. JavaScript: Describing Data Structures Through Object Conventions
function printUser(user) {
console.log(user.id);
console.log(user.name);
}
const user = {
id: 1,
name: "Alice"
};
printUser(user);
JavaScript does not statically check before the call whether user has id and name properties.
If the passed-in data lacks properties, it may cause an exception at runtime or result in undefined.
2. TypeScript: Using interface
interface User {
id: number;
name: string;
email?: string;
}
function printUser(user: User): void {
console.log(user.id);
console.log(user.name);
}
const user: User = {
id: 1,
name: "Alice"
};
printUser(user);
Here:
idis a required property.nameis a required property.email?is an optional property.voidindicates that the function does not return a meaningful value.
TypeScript verifies whether the object satisfies the interface structure during static checking.
3. TypeScript: Using type
type can define object types, and can also express union types, intersection types, function types, etc.
type User = {
id: number;
name: string;
};
type Status = "pending" | "success" | "failed";
type UserId = number | string;
interface and type have overlapping capabilities, but they are not exactly the same.
| Comparison Aspect | interface | type |
|---|---|---|
| Object structure | Supported | Supported |
| Union types | Not directly supported | Supported |
| Intersection types | Can be combined through inheritance | Supported |
| Declaration merging | Supported | Does not support merging duplicate declarations |
| Class implementation | Can use implements |
Object structure types can also be used with implements |
| Use cases | Object contracts, extensible interfaces | Union types, complex type composition, type aliases |
For example, an interface can be extended through inheritance:
interface User {
id: number;
}
interface Admin extends User {
permissions: string[];
}
Type aliases can be composed using intersection types:
type User = {
id: number;
};
type Admin = User & {
permissions: string[];
};
In engineering practice, you can use interface to describe extensible object contracts, and use type to express union types and complex type compositions. This is a common convention, not a mandatory rule.
V. Differences in Function Definitions
Both JavaScript and TypeScript support functions, arrow functions, closures, and higher-order functions, but TypeScript can further constrain parameters and return values.
1. JavaScript Functions
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice"));
JavaScript does not constrain the type of name at the definition stage.
2. TypeScript Functions
function greet(name: string): string {
return "Hello, " + name;
}
console.log(greet("Alice"));
TypeScript can check the types of parameters and return values.
3. Function Types
TypeScript can define function signatures separately:
type Calculator = (
a: number,
b: number
) => number;
const add: Calculator = (a, b) => {
return a + b;
};
This ensures that functions assigned to Calculator conform to the contract.
4. Optional Parameters and Default Parameters
function createUser(
name: string,
age?: number
): void {
console.log(name, age);
}
createUser("Alice");
createUser("Bob", 25);
Here:
age?: numberindicates that the parameter can be omitted.- Default parameters can be set using
age = 18. - Optional parameters and default parameters are different syntactic concepts, but both allow parameters to be omitted when calling.
5. Function Overloading
TypeScript supports function overload declarations, which can describe different call forms according to parameter forms.
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
return String(value);
}
format("Hello");
format(100);
The overload signatures here are used for static type checking; what actually executes is still a single JavaScript function implementation.
JavaScript does not have TypeScript's static function overload signature mechanism; it usually implements similar behavior by checking parameters.
6. Differences in Generic Capabilities
Generics are an important part of the TypeScript type system.
They allow developers to write reusable type logic while preserving the type relationship between input and output.
JavaScript can implement generic logic through functions and objects, but it has no native static generic type parameter mechanism.
1. JavaScript General-Purpose Functions
function identity(value) {
return value;
}
const a = identity(100);
const b = identity("Hello");
JavaScript can handle data of different types, but it cannot describe the constraint relationship between input types and return types at the static stage.
2. TypeScript Generic Functions
function identity<T>(value: T): T {
return value;
}
const a = identity<number>(100);
const b = identity<string>("Hello");
Here:
Tis a type parameter.- The input parameter uses type
T. - The return value also uses type
T. - When calling, you can explicitly specify the type parameter, or the compiler can infer it.
Generics can preserve type information while reusing code.
3. Generic Constraints
interface HasLength {
length: number;
}
function printLength<T extends HasLength>(
value: T
): number {
return value.length;
}
printLength("Hello");
printLength([1, 2, 3]);
// Type error
// printLength(100);
extends here indicates a generic constraint.
Only types with a length property can satisfy this constraint.
7. Differences in Compilation and Execution Mechanisms
This is a very important point for understanding JavaScript and TypeScript.
JavaScript can usually be handed directly to the JavaScript runtime for execution, whereas TypeScript usually needs to go through type checking and transpilation first.
1. JavaScript Execution Flow
flowchart TD
A["JavaScript Source Code"] --> B["JavaScript Runtime"]
B --> C["Parsing and Execution"]
C --> D["Execution Result"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
The JavaScript runtime is responsible for parsing and executing code, and depending on the specific implementation, it uses techniques such as interpretation and JIT compilation.
2. TypeScript Compilation Flow
flowchart TD
A["TypeScript source code"] --> B["Syntax parsing"]
B --> C["Build type information"]
C --> D["Static type checking"]
D --> E{"Are there errors that block the build?"}
E -->|"Yes"| F["Report type errors"]
E -->|"No"| G["Transpile to JavaScript"]
G --> H["JavaScript runtime"]
H --> I["Program execution"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
There are a few details to note:
- The TypeScript compiler can perform type checking and JavaScript transpilation.
- By default,
tsccan still emit JavaScript after reporting some type errors, depending on the build configuration. - Developers can use configurations such as
noEmitOnErrorto control whether files are emitted when errors exist. - Modern toolchains can also use tools such as esbuild, SWC, and Babel to transpile TypeScript, but these tools are not necessarily responsible for complete TypeScript type checking.
- Type checking and code transpilation are two different responsibilities; you cannot assume that code that transpiles successfully has necessarily passed type checking.
3. TypeScript does not need a standalone runtime
In the end, TypeScript usually runs in a JavaScript runtime.
For example:
const message: string = "Hello TypeScript";
console.log(message);
After transpilation:
const message = "Hello TypeScript";
console.log(message);
Browsers do not need to understand TypeScript type declarations such as string.
It is worth adding that some toolchains support directly executing or loading TypeScript files, but internally they still need to handle TypeScript syntax. Some newer versions of TypeScript also support runtime syntax features that can be preserved, so not all TypeScript syntax can simply be understood as pure type declarations.
VIII. Type Safety and Runtime Validation
TypeScript can improve type safety during development, but it cannot guarantee that all runtime data is correct.
This is a very common misconception in real-world engineering.
1. TypeScript types do not automatically validate external data
For example:
interface User {
id: number;
name: string;
}
async function getUser(): Promise<User> {
const response = await fetch("/api/user");
return response.json();
}
This code declares the return value as Promise<User>, but the data actually returned by the server does not necessarily match the structure of User.
response.json() yields runtime data; TypeScript type declarations do not automatically check its fields.
Therefore, the following situations can still occur:
idis actually a string.- The
namefield does not exist. - The server returns the wrong data structure.
- The API returns
nullor another unexpected value.
2. Use runtime validation
Runtime validation libraries such as Zod can be used to validate external data.
import { z } from "zod";
const UserSchema = z.object({
id: z.number(),
name: z.string()
});
type User = z.infer<typeof UserSchema>;
async function getUser(): Promise<User> {
const response = await fetch("/api/user");
const data: unknown = await response.json();
return UserSchema.parse(data);
}
The key here is:
unknownindicates data whose type has not yet been confirmed.UserSchema.parse()validates the actual data at runtime.- Only after successful validation does the data conform to the expected structure.
- If validation fails, an exception is thrown.
TypeScript handles static type checking, while runtime validation checks the real data; the two solve problems at different levels.
3. How Static Checking and Runtime Validation Work Together
flowchart TD
A["Receive external data"] --> B["Mark as unknown"]
B --> C["Runtime data validation"]
C --> D{"Does the data match the structure?"}
D -->|"No"| E["Return validation error"]
D -->|"Yes"| F["Obtain trusted typed data"]
F --> G["Execute business logic"]
G --> H["TypeScript static type checking"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px