TypeScript is a strictly typed superset of JavaScript developed by Microsoft. It adds a type system, interfaces, generics, and decorators while maintaining full compatibility with existing JS code. By checking types at compile time, TypeScript prevents a whole class of errors in React Native, Angular, and other frameworks. According to the State of JS Survey (2025), 78% of surveyed developers use TypeScript. Learn more in the TypeScript documentation.
Key Takeaways
TypeScript is a programming language from Microsoft (2012) created by Anders Hejlsberg (the creator of C# and Turbo Pascal). TypeScript extends JavaScript with a static type system, interfaces, generics, enums, and decorators. TS code compiles to plain JavaScript (transpilation) via the tsc compiler or Babel — the output is standard JS that runs in any environment.
The motivation behind TypeScript is the limitation of JavaScript in large projects. JavaScript's dynamic typing leads to errors that are only discovered at runtime: undefined is not a function, Cannot read property of null. TypeScript shifts type checking to compile time, preventing these errors before code execution. The larger the project, the greater the benefits of TS: in a codebase of 100,000+ lines, TS prevents hundreds of potential bugs.
A key feature of TypeScript is strict typing with the optional strict: true flag in tsconfig.json. Strict mode enables all checks: strictNullChecks (null/undefined are incompatible with other types), noImplicitAny (disallows implicit any), strictFunctionTypes (contravariance of function parameters). By default, strict: true is recommended for all new projects.
TypeScript differs from JavaScript only at development time. After compilation, types are erased — the runtime executes plain JS with no performance loss. This is a trade-off: development requires an extra compilation step, but provides IDE autocompletion, refactoring with symbol renaming, and type documentation directly in the code.
| Aspect | JavaScript | TypeScript |
|---|---|---|
| Typing | Dynamic, runtime | Static, compile-time |
| File extension | .js | .ts (or .tsx for React) |
| Type errors | Discovered at runtime | Discovered before execution |
| Generics | No | Yes (Generic types) |
| Interfaces | No (JSDoc only) | Yes (interface + type) |
| Compilation | Not required | Required (tsc / Babel) |
TypeScript's type system is structural, not nominal: two types are compatible if their structure matches, regardless of name. This differs from Java/C# where compatibility is determined by class or interface name. Structural typing simplifies integration with existing JS code — there is no need to declare implements for every type.
TypeScript supports primitive JS types plus: any (disables checking), unknown (safe any — requires checks before use), never (never returns), void (no return), tuple (fixed-length array), enum (enumeration), union (string | number), intersection (A & B), literal ('red' | 'blue'), index signature ([key: string]: number).
// Basic TypeScript type system
// Primitive types
const name: string = 'React Native';
const version: number = 0.73;
const isReady: boolean = true;
// Union and Literal types
type Platform = 'ios' | 'android' | 'web';
type Status = 'idle' | 'loading' | 'success' | 'error';
function getSDKVersion(platform: Platform): number {
switch (platform) {
case 'ios': return 17;
case 'android': return 34;
case 'web': return 2025;
}
}
// Tuple — fixed-length tuple
type Coordinate = [number, number];
const position: Coordinate = [55.75, 37.61];
// Enum — auto-increment enumeration
enum AppState {
Background,
Foreground,
Inactive
}
// Unknown — safe alternative to any
function parseJSON(json: string): unknown {
return JSON.parse(json);
}
const data = parseJSON('{"name":"TS"}');
if (typeof data === 'object' && data !== null) {
console.log((data as Record<string, unknown>).name);
}The Platform type is a union of string literals, restricting values to three options. If you pass 'windows', TypeScript will throw an error. The Coordinate tuple guarantees exactly two numbers — useful for coordinates or RGB colors. The AppState enum compiles to an object with reverse mapping. Unknown forces type checking before use — unlike any, unknown is safe by default.
Interfaces and type aliases in TypeScript describe object shapes. Interfaces support declaration merging (re-declaring adds fields) and extension (extends). Type aliases can describe unions, intersections, tuples, and conditional types but do not support declaration merging. Rule: use interfaces for API objects, type for everything else.
// Interfaces and types for React Native
// Interface with optional fields
interface User {
id: string;
name: string;
email: string;
avatar?: string; // optional field
readonly createdAt: Date; // read-only
}
// Interface extension (extends)
interface AdminUser extends User {
role: 'admin';
permissions: string[];
}
// Type for API data
type ApiResponse<T> = {
data: T;
status: Status;
error?: string;
};
// Utility types — Partial makes all fields optional
type PartialUser = Partial<User>;
// Pick — selects specified fields
type UserPreview = Pick<User, 'id' | 'name' | 'avatar'>;
// Record — dictionary with typed keys
type UserMap = Record<string, User>;The User interface with ? (optional field) and readonly (read-only). ApiResponse<T> is a generic interface for API responses. Partial<User> is a utility type making all fields optional (useful for edit forms). Pick<User, 'id' | 'name'> selects only specified fields — convenient for preview components. Record<string, User> is a user dictionary by ID.
Generics are a key feature of TypeScript, allowing you to create components that work with any type without losing type safety. A generic function is defined with a type parameter in angle brackets: function identity<T>(arg: T): T. The type T is inferred automatically from the argument or specified explicitly: identity<string>('hello').
Utility types are built-in generics for type transformations: Partial<T> (all fields optional), Required<T> (all fields required), Readonly<T> (all fields readonly), Pick<T, K> (select fields), Omit<T, K> (exclude fields), Record<K, T> (dictionary), Exclude<T, U> (exclude from union), Extract<T, U> (extract from union), NonNullable<T> (exclude null/undefined).
// Generics in TypeScript
// Generic function for working with API
async function fetchData<T>(url: string): Promise<T> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json() as Promise<T>;
}
// Usage with a specific type
interface Product {
id: number;
title: string;
price: number;
}
const products = await fetchData<Product[]>('/api/products');
// Generic class for state management
class StateManager<S> {
private state: S;
constructor(initial: S) {
this.state = initial;
}
getState(): S {
return this.state;
}
updateState(partial: Partial<S>): void {
this.state = { ...this.state, ...partial };
}
}
// Typed work with Redux Reducer
type Action<T, P> = {
type: T;
payload: P;
};
type UserAction =
| Action<'SET_USER', User>
| Action<'CLEAR_USER', undefined>
| Action<'UPDATE_USER', Partial<User>>;The fetchData<T> function is a typed wrapper around fetch. The T parameter determines the response shape: when calling fetchData<Product[]>, TypeScript knows the returned array contains Product objects. The StateManager<S> class manages state of any type — Partial<S> for partial updates. Action<T, P> is a discriminated union for Redux actions with automatic type narrowing in switch.
TypeScript in React Native provides strict typing for component props and state. The React Native CLI creates a template with .tsx extension and tsconfig.json. PropTypes (JS) are replaced by TypeScript interfaces — checking is done at compile time, not at runtime. styled-components and React Navigation have full type support.
React.FC<Props> is the type for a functional component with props. Children are automatically typed. useRef<T> — reference to a native component. useState<S> — state with type inference. useNavigation<T> — typed navigation. useCallback, useMemo — with automatic type inference. All React hooks are fully typed.
// Typed React Native component
import React, { useState, useCallback } from 'react';
import {
View, Text, FlatList, TouchableOpacity,
StyleSheet
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
// Types for navigation and data
type RootStackParamList = {
Home: undefined;
Profile: { userId: string };
Settings: undefined;
};
type NavigationProp =
NativeStackNavigationProp<RootStackParamList, 'Home'>;
// Interface for props
interface ProductListProps {
products: Product[];
onSelect: (id: number) => void;
}
// Typed functional component
const ProductList: React.FC<ProductListProps> = ({
products,
onSelect
}) => {
const navigation = useNavigation<NavigationProp>();
const [selectedId, setSelectedId] = useState<number | null>(null);
const handlePress = useCallback((id: number) => {
setSelectedId(id);
onSelect(id);
navigation.navigate('Profile', { userId: String(id) });
}, [onSelect, navigation]);
const renderItem = useCallback(({ item }: { item: Product }) => (
<TouchableOpacity onPress={() => handlePress(item.id)}>
<Text>{item.title}</Text>
<Text>${item.price.toFixed(2)}</Text>
</TouchableOpacity>
), [handlePress]);
return (
<FlatList
data={products}
renderItem={renderItem}
keyExtractor={(item) => String(item.id)}
/>
);
};The RootStackParamList type is a dictionary of routes with their parameters. NavigationProp provides typed navigation: navigation.navigate('Profile', { userId }) verifies that Profile accepts userId. useCallback with typed parameters prevents unnecessary re-renders. FlatList is typed via generics:
TypeScript tools include the tsc compiler, tsconfig.json, IDE support in VS Code, ESLint with @typescript-eslint, Prettier, and DefinitelyTyped (@types/*). tsc is the compiler that converts .ts to .js. tsconfig.json configures: target (ES2020), module (ESNext), strict: true, outDir (output folder). sourceMap — debugging TS in the browser via code maps.
DefinitelyTyped is a repository of type definitions for libraries without built-in types. Installation: npm install @types/react @types/react-native --save-dev. .d.ts files are type declarations. Modern libraries (React, React Native, Angular) include built-in types and do not require @types/. For older JS libraries, DefinitelyTyped is the only source of types.
// tsconfig.json — minimal configuration
{
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"strict": true,
"jsx": "react-native",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"noEmit": true // only check, no JS generation
},
"include": ["src/**/*.ts", "src/**/*.tsx"],
"exclude": ["node_modules", "babel.config.js"]
}The strict: true option enables all type checks — recommended for all projects. jsx: 'react-native' preserves JSX without transformation (React Native handles JSX via Babel). moduleResolution: 'node' — module resolution as in Node.js. esModuleInterop — compatibility with CommonJS modules. noEmit: true — only check without generating JS files (Babel or Metro generates JS).
Frequently Asked Questions
TypeScript is a strictly typed superset of JavaScript from Microsoft (2012). It adds static typing, interfaces, generics, enums, and decorators. It compiles to plain JS via tsc. Compatible with any JS code. Used in React Native (~65% of new projects), Angular, and Node.js. Created by Anders Hejlsberg (creator of C#).
TypeScript provides strict typing for props and state of React components — type errors are caught at compile time, not at runtime. IDE autocompletion works for all libraries. Generics type complex structures (Redux store, API). React Navigation has full route typing. According to surveys, 78% of JS developers use TypeScript.
The tsc compiler parses .ts/.tsx files, checks types, removes annotations, and generates .js. The target (ES5, ES2020) is set in tsconfig.json. TypeScript does not change the runtime — erased types do not affect performance. Source maps link compiled JS to the original TS for debugging. Babel with @babel/preset-typescript is an alternative to tsc.
TypeScript includes all JS types: string, number, boolean, null, undefined, symbol, any. It adds: void, never, unknown, tuple, enum, union (string | number), intersection (A & B), literal ('red' | 'blue'), Record, Pick, Omit, Partial, Required, Readonly, Extract, Exclude, NonNullable. Generics create generalized types: Array<number>, Promise<string>, Map<string, User>.
The tsc compiler is included in the typescript npm package. VS Code — IDE with native TS support, autocompletion, refactoring. tsconfig.json configures strict mode. ESLint with @typescript-eslint/parser — static analysis. Prettier — formatting. DefinitelyTyped (@types/*) — types for libraries without built-in support. React Native CLI includes a TypeScript template.
Summary
We will develop a mobile application turnkey
IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.
Read also