TypeScript Introduction
TypeScript is an open-source programming language developed by Microsoft. It is a superset of JavaScript that, while fully compatible with JavaScript syntax, adds an optional static type system and class-based object-oriented programming capabilities.
TypeScript code is eventually compiled to pure JavaScript and can run in any environment that supports JavaScript, including browsers, Node.js, and mobile.

Why TypeScript is needed
JavaScript is a dynamically typed language, where a variable's type is determined only at runtime.
This flexibility works well in small projects, but as projects grow, problems gradually surface:
| Problem Scenario | JavaScript's dilemmas | TypeScript's solutions |
|---|---|---|
| Wrong type passed to a function parameter | Error only appears at runtime, hard to detect early | Error reported at compile time, with real-time IDE hints |
| Accessing a non-existent property | Return undefined, with unpredictable behavior |
The compiler reports an error directly and refuses to compile |
| Large-scale project refactoring | Change one place, never know what will break | The type system automatically tracks all references |
| Team collaboration | What parameters a function accepts and what it returns relies entirely on comments or documentation | Type signatures serve as documentation, with automatic IDE completion |
| Code Readability | Cannot directly know the data structure from a function definition | Interfaces and type aliases make data structures clear at a glance |
TypeScript's essential goal is not to replace JavaScript, but to make large-scale JavaScript projects manageable and maintainable. It is a "safety net" for JavaScript, not a competitor.
Let's look at the most intuitive example:
Example
// JavaScript: errors only appear at runtime
function
greet
(
name
)
{
return
"Hello, "
name.
toUpperCase
(
)
;
}
greet
(
123
)
;
// Runtime error: name.toUpperCase is not a function
Example
// TypeScript: errors are caught at compile time
function
greet
(
name
:
string
)
:
string
{
return
"Hello, "
name.
toUpperCase
(
)
;
}
greet
(
123
)
;
// Compilation error: Argument of type 'number' is not assignable to parameter of type 'string'
greet
(
"runoob"
)
;
// Correct: Hello, RUNOOB
The relationship between TypeScript and JavaScript
The relationship between TypeScript and JavaScript can be summed up in one sentence: TypeScript is a superset of JavaScript, meaning all valid JavaScript code is also valid TypeScript code.
Set relationship diagram
JavaScript (all JS code)
⊂ TypeScript (JS + type system + new features)
⊂ Compiled output (standard JavaScript, runnable in any environment)
The core differences between the two:
| Comparison Item | JavaScript | TypeScript |
|---|---|---|
| Type system | Dynamic typing, determined at runtime | Static typing, checked at compile time (optional) |
| How to run | Runs directly in the browser / Node.js | Must be compiled to JS before running |
| When errors are discovered | Runtime | Compile time (early detection) |
| IDE support | Basic completion | Strong type inference, precise completion, refactoring support |
| Learning curve | Gentler | Requires learning an additional type system |
| Existing JS compatibility | — | Fully compatible, supports progressive migration |
| File extension | .js |
.ts or .tsx(including JSX) |
TypeScript supports "progressive adoption": you don't have to rewrite the entire project at once. You can first
.jsto.ts, then gradually add types to key modules, while existing code keeps running.
Core Features
TypeScript introduces a complete type system on top of JavaScript; the following are the most commonly used core features.
Basic type annotations
Declare a type with a colon after variables, function parameters, and return values; this is the most basic syntax in TypeScript.
Example
// Basic types: number, string, boolean, null, undefined, symbol, bigint
let age
:
number
=
25
;
let username
:
string
=
"runoob"
;
let isActive
:
boolean
=
true
;
// Array types, two equivalent forms
let scores
:
number
[
]
=
[
90
,
85
,
92
]
;
let tags
:
Array
<
string
=
[
"typescript"
,
"javascript"
];
// Tuple: an array with fixed length and types
let point
:
[
number
,
number
]
=
[
10
,
20
]
;
let entry
:
[
string
,
number
]
=
[
"RUNOOB"
,
100
]
;
// Function: parameter types + return type
function
add
(
a
:
number
,
b
:
number
)
:
number
{
return
a
b
;
}
// void: the function has no return value
function
log
(
msg
:
string
)
:
void
{
console.
log
(
msg
)
;
}
// Optional parameter: add ? after the parameter name
function
greet
(
name
:
string
,
title
?:
string
)
:
string
{
return
title
?
`$
{
title
}
$
{
name
}
`
:
name
;
}
console.
log
(
greet
(
"RUNOOB"
)
)
;
// Output: RUNOOB
console.
log
(
greet
(
"runoob"
,
"Mr."
)
)
;
// Output: Mr. runoob
Interface
An interface describes the "shape" of an object, defining which properties and methods an object should have.
Example
// Define an interface: describe the structure of a user object
interface
User
{
id
:
number
;
// Required
name
:
string
;
// Required
?:
string
;
// Optional, marked with ?
readonly role
:
string
;
// Readonly, cannot be modified after assignment
}
// Use the interface type for function parameters
function
printUser
(
user
:
User
)
:
void
{
console.
log
(
`ID
:
$
{
user.
id
}
,
Name
:
$
{
user.
name
}
`
)
;
if
(
user.
)
{
console.
log
(
:
$
{
user.
}
`
)
;
}
}
const
admin
:
User
=
{
id
:
1
,
name
:
"RUNOOB"
,
:
"runoob@example.com"
,
role
:
"admin"
,
}
;
printUser
(
admin
)
;
// Output: ID: 1, Name: RUNOOB
// Output: Email: runoob@example.com
// admin.role = "user"; // Error: Cannot assign to 'role' because it is a read-only property.
// Interface inheritance
interface
AdminUser
extends
User
{
permissions
:
string
[
]
;
}
Type alias
A type alias is created with the type keyword and can define an alias for any type, including complex structures such as union and intersection types.
Example
// Union type: a variable can be one of several types
type ID
=
string
|
number
;
let userId
:
ID
=
"abc-123"
;
// valid
userId
=
456
;
// also valid
// Literal type: restrict a variable to specific values
type Direction
=
"up"
|
"down"
|
"left"
|
"right"
;
type Status
=
"pending"
|
"active"
|
"inactive"
;
function
move
(
dir
:
Direction
)
:
void
{
console.
log
(
`Moving $
{
dir
}
`
)
;
}
move
(
"up"
)
;
// Correct
// move("diagonal"); // Error: not within the literal range
// Intersection type: combine multiple types
type WithTimestamp
=
{
createdAt
:
Date
;
updatedAt
:
Date
;
}
;
type UserRecord
=
User
&
WithTimestamp
;
// Has all properties of both User and WithTimestamp
// Function type alias
type Transformer
<
T
,
U
=
(
input:
T
)
=>
U
;
const
toNumber
:
Transformer
<
string
,
number
=
(
s
)
=>
parseInt
(
s
,
10
);
Generics
Generics allow writing reusable components while maintaining type safety. You can think of generics as "variables for types"—the concrete type is passed in at use time.
Example
// Without generics: can only handle the number type
function
firstNumber
(
arr
:
number
[
]
)
:
number
{
return
arr
[
0
]
;
}
// With generics: T is a type parameter, determined at call time
function
first
<
T
(
arr:
T
[
]
)
:
T
{
return
arr
[
0
]
;
}
const
n
=
first
<
number
(
[
1
,
2
,
3
]
);
// n is of type number
const
s
=
first
<
string
(
[
"a"
,
"b"
]
);
// s is of type string
const
inferred
=
first
(
[
true
,
false
]
)
;
// TypeScript automatically infers T as boolean
// Generic interface
interface
ApiResponse
<
T
{
data:
T
;
status
:
number
;
message
:
string
;
}
// Using a generic interface
const
userResponse
:
ApiResponse
<
User
=
{
data:
{
id
:
1
,
name
:
"RUNOOB"
,
role
:
"admin"
}
,
status
:
200
,
message
:
"success"
,
}
;
// Generic constraint: restrict T to having an id property
function
getById
<
T
extends
{
id:
number
}
(
items
:
T
[
]
,
id
:
number
)
:
T
|
undefined
{
return
items.
find
(
item
=>
item.
id
===
id
)
;
}
Enum
Enums are used to define a set of named constants, making "magic numbers" or "magic strings" in code meaningful.
Example
// Numeric enum (auto-increments from 0 by default)
enum
Direction
{
Up
,
// 0
Down
,
// 1
Left
,
// 2
Right
,
// 3
}
console.
log
(
Direction.
Up
)
;
// Output: 0
console.
log
(
Direction
[
0
]
)
;
// Output: "Up" (reverse mapping)
// String enum (more recommended, values are more readable when debugging)
enum
Color
{
Red
=
"RED"
,
Green
=
"GREEN"
,
Blue
=
"BLUE"
,
}
function
paint
(
color
:
Color
)
:
void
{
console.
log
(
`Painting
in
$
{
color
}
`
)
;
}
paint
(
Color.
Red
)
;
// Output: Painting in RED
// paint("red"); // Error: the string "red" is not of type Color
// const enum: inlined after compilation, reducing runtime overhead
const
enum
HttpStatus
{
OK
=
200
,
NotFound
=
404
,
InternalError
=
500
,
}
const
status
:
HttpStatus
=
HttpStatus.
OK
;
// Directly replaced with the number 200 after compilation
Type Inference
TypeScript does not require manually annotating every variable; the compiler infers types automatically from assignments.
Example
// TypeScript automatically infers variable types, no explicit annotation needed
let count
=
0
;
// Inferred as number
let name
=
"RUNOOB"
;
// Inferred as string
let flag
=
true
;
// Inferred as boolean
// Infer array element type
let numbers
=
[
1
,
2
,
3
]
;
// Inferred as number[]
// Infer function return type
function
double
(
n
:
number
)
{
// Return value automatically inferred as number
return
n
2
;
}
// Object literal inference
const
config
=
{
host
:
"localhost"
,
// string
port
:
3000
,
// number
debug
:
false
,
// boolean
}
;
// config.port = "3000"; // Error: Type 'string' is not assignable to type 'number'.
A practical tip: function parameters usually need explicit type annotations (because callers cannot infer types from parameter values), while local variables and return values inside the function body mostly rely on inference and do not all need manual annotation.
Classes and access modifiers
TypeScript fully supports ES6 class syntax and adds four access modifiers: public, private, protected, and readonly.
Example
class
Animal
{
readonly name
:
string
;
// Readonly, cannot be modified after initialization
private age
:
number
;
// Private, accessible only within the class
protected species
:
string
;
// Protected, accessible to subclasses
constructor
(
name
:
string
,
age
:
number
,
species
:
string
)
{
this
.
name
=
name
;
this
.
age
=
age
;
this
.
species
=
species
;
}
// public method (public by default, can be omitted)
public introduce
(
)
:
string
{
return
`I
'm ${this.name}, a ${this.species}.`;
}
// getter: call a method like accessing a property
get info(): string {
return ${this.name} (${this.age} years old);
}
}
class Dog extends Animal {
private breed: string;
constructor(name: string, age: number, breed: string) {
super(name, age, "Canis lupus familiaris"); // call the parent class constructor
this.breed = breed;
}
// Subclasses can access protected properties
describe(): string {
return ${this.name} is a ${this.species}, breed: ${this.breed};
}
}
const dog = new Dog("RUNOOB", 3, "Labrador");
console.log(dog.introduce()); // Output: I'
m RUNOOB
,
a Canis lupus familiaris.
console
.
log
(
dog.
info
)
;
// Output: RUNOOB (3 years old)
// console.log(dog.age); // Error: private property cannot be accessed from outside
Decorator
A decorator is a metaprogramming syntax used to attach extra behavior to classes, methods, and properties; it is common in frameworks such as Angular and NestJS.
TypeScript 5.0 has implemented decorators as an official standard (Stage 3 proposal), no longer requiring you to enable experimentalDecorators flag is set.
Example
// Class decorator: executed when the class is defined
function
sealed
(
constructor
:
Function
)
{
Object
.
seal
(
constructor
)
;
// Forbid adding new properties
Object
.
seal
(
constructor.
prototype
)
;
}
// Method decorator: can be used for logging, permission checks, etc.
function
log
(
target
:
any
,
propertyKey
:
string
,
descriptor
:
PropertyDescriptor
)
{
const
original
=
descriptor.
value
;
descriptor.
value
=
function
(
...
args
:
any
[
]
)
{
console.
log
(
`Calling $
{
propertyKey
}
with args
:
`
,
args
)
;
const
result
=
original.
apply
(
this
,
args
)
;
console.
log
(
`$
{
propertyKey
}
returned
:
`
,
result
)
;
return
result
;
}
;
}
@
sealed
class
Calculator
{
@
log
add
(
a
:
number
,
b
:
number
)
:
number
{
return
a
b
;
}
}
const
calc
=
new
Calculator
(
)
;
calc.
add
(
1
,
2
)
;
// Output: Calling add with args: [ 1, 2 ]
// Output: add returned: 3
Application Areas
Thanks to its full compatibility with JavaScript, TypeScript can be used almost anywhere JavaScript runs, and brings extra benefits in large projects.
Front-end web development
This is the most widely used scenario for TypeScript. All three major front-end frameworks provide first-class support for TypeScript:
| Framework | TypeScript support status | Typical scenario |
|---|---|---|
| Angular | Official language, TypeScript is used by default and cannot be bypassed | Enterprise SPAs and admin management systems |
| React | Officially provides @types/react, and both Create React App and Vite have built-in TypeScript templates |
E-commerce, content platforms, and mid- to back-office applications |
| Vue | Vue 3's core code was rewritten in TypeScript, and the Composition API significantly improves TypeScript-friendliness | Small and medium-sized projects, progressive migration |
| Next.js / Nuxt | Built-in TypeScript support, enabled by default in new projects | Full-stack SSR/SSG applications |
Back-end Node.js development
TypeScript is equally popular in Node.js back-end development. NestJS is currently the most popular TypeScript back-end framework, adopting a modular architecture similar to Angular's, with built-in dependency injection and decorator support.
In addition, the Deno runtime has natively supported TypeScript from day one, allowing it to run directly without any configuration .ts files. Bun also has built-in TypeScript support.
Command-Line Tools and Scripts
With the help of ts-node、tsx and similar tools, TypeScript code can be executed directly without precompilation, making it ideal for writing build scripts and CLI tools.
Mobile and Cross-Platform
React Native fully supports TypeScript, and many enterprise-grade mobile applications (such as the mobile version of Microsoft Office, Shopify, and others) use this technology stack. Expo's new project templates are also based on TypeScript by default.
Game Development and Graphics
Babylon.js (a 3D engine from Microsoft) is written entirely in TypeScript and treats TypeScript type definitions as first-class citizens. 2D game engines such as Phaser also provide complete type definitions.
Development History
The birth and growth of TypeScript is closely tied to the evolution of the JavaScript ecosystem, and every major release was driven by clear engineering needs.
Origins (2010 - 2012)
The story of TypeScript began with an engineering challenge inside Microsoft: how to make large JavaScript projects maintainable.
The designer Anders Hejlsberg was an industry legend—the chief architect of C# and the creator of Turbo Pascal and Delphi. He began designing the language around 2010, with the core goal of introducing static type checking without breaking JavaScript compatibility.
Another context for Microsoft's introduction of TypeScript was the release of Windows 8—applications could be developed with HTML + JavaScript, and Microsoft wanted to attract .NET programmers, so many of TypeScript's syntax choices were intentionally kept close to C# and .NET.
In October 2012, TypeScript 0.8 was publicly released, after about two years of internal development at Microsoft.
Early Versions (2013 - 2015)
| Time | Version | Key Events |
|---|---|---|
| 2013-06 | 0.9 | Official stable release, with major performance improvements and better IDE integration |
| 2014-04 | 1.0 | The first official stable version, introducing classes, interfaces, and modules, with support for compiling to standard JavaScript |
| 2014-07 | — | The TypeScript compiler source code was open-sourced, hosted on GitHub, and accepted community contributions |
| 2015-04 | — | Microsoft released Visual Studio Code, with deep built-in support for TypeScript, and the two complemented each other |
| 2015-07 | 1.5 | Introduced support for ES6 module syntax, decorators (experimental), and namespaces |
Rapid Growth (2016 - 2019)
This stage was a critical period in which TypeScript moved from a niche tool to the mainstream, driven mainly by the choices of the framework ecosystem.
| Time | Version / Event | Milestone Significance |
|---|---|---|
| 2016-09 | TypeScript 2.0 | Introduced non-null types (--strictNullChecks), one of the most important features of TypeScript's type safety; introduced tagged union types |
| 2016 | Release of Angular 2 | Google's Angular team announced the adoption of TypeScript as its official development language, bringing TypeScript into the public eye |
| 2017 | TypeScript 2.x Series | Conditional types, mapped types, and the infer keyword were introduced one after another, greatly enhancing the expressive power of the type system |
| 2018-07 | TypeScript 3.0 | Project References, supporting large monorepos; introduced the unknown type (a safer top type than any) |
| 2019 | DefinitelyTyped | The community-maintained type definition repository DefinitelyTyped (@types/*) contains over 7,000 packages, covering essentially all mainstream npm libraries |
Maturity and Popularity (2020 - 2022)
| Time | Version / Event | Key Content |
|---|---|---|
| 2020-08 | TypeScript 4.0 | Variadic tuple types, labeled tuple elements; significantly improved editor experience |
| 2021 | TypeScript 4.x Series | Template Literal Types, enhanced built-in utility types,noImplicitOverride and other strict-mode enhancements |
| 2022 | State of JS Survey | TypeScript's usage surpassed pure JavaScript for the first time, becoming the most popular superset language in the JS ecosystem |
| 2022 | Popularization of Vue 3 / Vite | The Vue 3 core was rewritten in TypeScript, and together with Vite brought the TypeScript experience in front-end engineering to new heights |
Modern Era (2023 to Present)
| Time | Version | Key Features |
|---|---|---|
| 2023-03 | TypeScript 5.0 | Modern decorators (Stage 3 standard), const type parameters, all enums upgraded to union enums, with significant performance improvements |
| 2023-08 | TypeScript 5.2 | Introduced Explicit Resource Management (using keyword), solving the problem of deterministic cleanup for resources such as database connections and file handles |
| 2024-03 | TypeScript 5.4 | Improved type narrowing in closures,NoInfer Tool Type |
| 2024-06 | TypeScript 5.5 | type predicate inference, and regular expression syntax checking, allowing the type system to understand code logic more precisely |
| 2024-11 | TypeScript 5.7 | Supported --target es2024, with more reliable detection of uninitialized variables |
| 2025-03 | TypeScript 5.8 | Enhanced return value checking for conditional and indexed access types; support for loading ESM modules under --module nodenext via require() (requires Node.js 22+) |
Future Outlook: Rewriting the Compiler in Go
In early 2025, Microsoft announced a major decision: to rewrite the TypeScript compiler in the Go language, with the project codenamed Corsa。
The official statement said the rewritten compiler is expected to be more than 10 times faster, reducing build times for large projects from minutes to seconds.
According to the plan, the Go version will be officially released as TypeScript 7.x, while current 5.x / 6.x versions of TypeScript will continue to be iterated on and maintained as normal. The refactoring is expected to be completed by the end of 2025.
This rewrite does not change the syntax or type system of the TypeScript language itself; it is a transparent upgrade for developers—your code needs no changes at all, only a significant boost in compilation speed.
Comparison of TypeScript with Other Strongly Typed Languages
If you have a background in other strongly typed languages, the following comparison can help you quickly grasp TypeScript's design philosophy.
| Comparison Item | TypeScript | Java / C# | Go |
|---|---|---|---|
| Type system | Structural typing (duck typing) | Nominal typing (inheritance relationships must be explicitly declared) | Structural typing (implicit interfaces) |
| Null safety | Enable strictNullChecks supported after |
Java requires annotations or Optional; supported in C# 8+ | via error values and nil checks |
| Generics | Supported, with syntax similar to Java/C# | Supported, though Java has type erasure limitations | Supported in Go 1.18+, with relatively concise syntax |
| Compilation output | JavaScript (runs in a JS environment) | Bytecode (runs on the JVM / CLR) | Native machine code |
| Runtime type checking | None (type information is erased after compilation) | Yes (via reflection) | None |
| Learning curve | Friendly to JS developers and can be adopted gradually | Steeper learning curve for beginners | Relatively concise, with a moderate learning curve |
TypeScript uses astructural type system(Structural Typing): as long as the "shape" of two types matches, they are considered compatible, with no need to explicitly declare an inheritance relationship. This is fundamentally different from the nominal typing of Java/C#, and is also the key reason TypeScript can interoperate seamlessly with JavaScript.
Limitations of TypeScript
TypeScript is not a silver bullet; understanding its boundaries is equally important.
| Limitation | Description | How to Address It |
|---|---|---|
| No types at runtime | All type information is erased after compilation, so you cannot rely on types to make decisions at runtime | Use when runtime validation is needed, such as zod、io-ts and other libraries |
| Compilation step | Compared with pure JS, there is an extra compilation step, which increases engineering complexity | Modern build tools (Vite, esbuild) already optimize this well |
| The any type escape hatch | Overuse of any renders type checking ineffective |
Enable noImplicitAny and strict pattern, together with ESLint rules |
| The barrier to type gymnastics | Complex conditional and mapped types are unfriendly to beginners | Most business code does not need advanced types; a step-by-step approach is fine |
| Third-party library support | A few older libraries lack type definitions, requiring you to write .d.ts files yourself | First check @types/*, and only write the declaration file by hand if there really is none |