JavaScript and TypeScript are closely related, but they are not the same.
JavaScript is the programming language browsers understand. TypeScript builds on JavaScript and adds a type system that can catch many mistakes before your code runs.
If you already understand JavaScript, TypeScript does not require you to start programming again from zero. Most of your JavaScript knowledge still applies.
The biggest change is that TypeScript lets you describe what kind of data your variables, function parameters, objects, and return values should contain.
Course Home: JavaScript Tutorial for Beginners
Previous Lesson: JavaScript Before Angular: What You Should Know First
Next Lesson: TypeScript for JavaScript Developers
Quick Answer
The simplest difference is:
JavaScript:
function add(a, b) {
return a + b;
}
TypeScript:
function add(
a: number,
b: number
): number {
return a + b;
}
The JavaScript function accepts any values.
The TypeScript version declares that:
ashould be a number.bshould be a number.- The function should return a number.
TypeScript can report a problem before execution when your code does this:
add(10, "5");
because "5" is a string instead of a number.
What Is JavaScript?
JavaScript is a programming language used extensively for web development.
It can:
- Add behavior to webpages
- Handle user events
- Change the DOM
- Validate forms
- Work with arrays and objects
- Make API requests
- Run asynchronous code
- Build browser applications
- Run outside browsers in environments such as Node.js
Example:
const product = {
name: "Keyboard",
price: 1500
};
console.log(
product.name
);
JavaScript determines value types while the program runs.
What Is TypeScript?
TypeScript is a language built on JavaScript.
Valid JavaScript concepts remain central to TypeScript, while TypeScript adds features for describing and checking types.
Example:
const productName: string =
"Keyboard";
const price: number =
1500;
const inStock: boolean =
true;
The type annotations are:
string
number
boolean
They tell TypeScript what values the variables are expected to contain.
TypeScript Builds on JavaScript
You do not throw away your JavaScript knowledge when you start TypeScript.
Concepts such as these still matter:
- Variables
- Functions
- Conditions
- Loops
- Arrays
- Objects
- Classes
- Modules
- Promises
- async/await
- Spread syntax
- Destructuring
TypeScript adds a type system around the same language foundation.
That is why learning JavaScript before Angular is useful.
JavaScript vs TypeScript at a Glance
| Feature | JavaScript | TypeScript |
|---|---|---|
| Type system | Dynamic | Static type checking on top of JavaScript |
| Type annotations | No | Yes |
| Interfaces | No TypeScript-style interfaces | Yes |
| Generics | No TypeScript type generics | Yes |
| Browser execution | Runs directly as JavaScript | TypeScript syntax is normally transformed into JavaScript first |
| Error detection | Many errors appear while running | Many type errors can appear during development |
| Editor assistance | Good | Often stronger with type information |
| JavaScript compatibility | It is JavaScript | Built on JavaScript |
| Common Angular use | Language foundation | Main language used for Angular application code |
The two languages are related rather than completely separate choices.
The Biggest Difference: Types
Consider this JavaScript:
let price = 1500;
price = "free";
JavaScript allows the reassignment.
The variable first contains a number.
Later it contains a string.
That flexibility is valid JavaScript.
Now TypeScript:
let price: number =
1500;
price = "free";
TypeScript reports a type error because:
"free"
is not a number.
This can catch mistakes before they become runtime bugs.
JavaScript Is Dynamically Typed
In JavaScript:
let value = 10;
value = "Ten";
value = true;
The same variable can contain values of different types during execution.
This is called dynamic typing.
Dynamic typing can be convenient, but large applications can become harder to reason about when developers are unsure what data a value should contain.
Review JavaScript Data Types if strings, numbers, booleans, null, and undefined are still unclear.
TypeScript Adds Static Type Checking
TypeScript lets you describe expected types.
Example:
let quantity: number =
1;
quantity = 2;
Valid.
This is not valid for the declared type:
quantity = "two";
The type checker can report the mismatch during development.
This does not mean every possible application bug disappears.
Types help catch a specific class of mistakes.
Your application still needs:
- Correct logic
- Runtime checks
- API validation
- Error handling
- Testing
- Security controls
Type Inference
You do not need to write a type annotation everywhere.
TypeScript can often infer the type.
Example:
const name = "Riya";
TypeScript can understand that name is a string.
Another:
let quantity = 1;
TypeScript can infer a numeric type.
Writing this is often unnecessary:
let quantity: number =
1;
when the type is already obvious.
Use explicit annotations when they improve clarity or define an important boundary.
JavaScript Variable Example
const productName =
"Keyboard";
let quantity = 1;
quantity = 2;
This is normal JavaScript.
TypeScript Variable Example
const productName: string =
"Keyboard";
let quantity: number =
1;
quantity = 2;
The code behaves similarly after TypeScript has been transformed into runnable JavaScript.
The added annotations help the development tools check your intent.
JavaScript Function Example
function calculateTotal(
price,
quantity
) {
return price * quantity;
}
Nothing in the function declaration tells you what type price should contain.
This call is possible:
calculateTotal(
"500",
2
);
JavaScript will apply its runtime conversion rules.
TypeScript Function Example
function calculateTotal(
price: number,
quantity: number
): number {
return price * quantity;
}
Now the function contract is clearer.
It expects:
number
number
and returns:
number
This call matches the contract:
calculateTotal(
500,
2
);
This does not:
calculateTotal(
"500",
2
);
Why Typed Function Parameters Matter
Large applications pass values through many functions.
Consider:
function calculateDiscount(
price: number,
percentage: number
): number {
return (
price *
percentage /
100
);
}
Another developer can quickly see what the function expects.
Editor tools can also provide better completion and warnings.
Typed function boundaries are one of TypeScript’s biggest practical benefits.
Function Return Types
You can declare what a function should return.
Example:
function getUserName(): string {
return "Riya";
}
This is valid.
This is not:
function getUserName(): string {
return 100;
}
The declared return type is:
string
but the returned value is a number.
void Return Type
A function that does not return a useful value can use:
void
Example:
function showMessage(
message: string
): void {
console.log(message);
}
The function performs an action rather than returning a result for another part of the program.
Typed Arrays
JavaScript:
const prices = [
500,
1000,
1500
];
TypeScript can describe the array as:
const prices: number[] = [
500,
1000,
1500
];
Now this does not match the declared type:
prices.push("free");
The array is expected to contain numbers.
Another Array Type Syntax
You may also see:
const prices:
Array<number> = [
500,
1000
];
This describes the same broad idea as:
number[]
Both forms are valid TypeScript.
For simple arrays, this is often easier to read:
number[]
Typed Object Example
JavaScript:
const product = {
id: 1,
name: "Keyboard",
price: 1500
};
TypeScript needs a way to describe the expected object shape when you want reusable type checking.
One option is an interface.
TypeScript Interface
interface Product {
id: number;
name: string;
price: number;
}
Now:
const product: Product = {
id: 1,
name: "Keyboard",
price: 1500
};
The interface describes the expected properties and their types.
What Is an Interface?
An interface can describe the shape of an object.
Example:
interface User {
id: number;
name: string;
email: string;
}
A matching object:
const user: User = {
id: 10,
name: "Riya",
email:
"riya@example.com"
};
If a required property is missing or has the wrong type, TypeScript can report it.
Missing Property Example
Interface:
interface Product {
id: number;
name: string;
price: number;
}
Object:
const product: Product = {
id: 1,
name: "Keyboard"
};
The required:
price
property is missing.
TypeScript can identify the problem during development.
Optional Properties
Use:
?
for an optional property.
Example:
interface User {
id: number;
name: string;
phone?: string;
}
This object is valid:
const user: User = {
id: 1,
name: "Amit"
};
phone can be absent.
Optional properties are common when API or form data has fields that are not always present.
readonly Properties
TypeScript can mark properties as:
readonly
Example:
interface Product {
readonly id: number;
name: string;
}
You can read:
product.id
but TypeScript prevents normal reassignment to that property through the typed reference.
This is a development-time type rule.
It does not automatically freeze the JavaScript object at runtime.
Interface vs JavaScript Object
An interface is TypeScript type information.
It does not become a normal JavaScript object in the browser.
This:
interface Product {
name: string;
}
helps TypeScript check code.
The interface itself is removed from the emitted JavaScript.
This is an important difference between type information and runtime data.
Type Aliases
TypeScript also provides type aliases.
Example:
type Product = {
id: number;
name: string;
price: number;
};
Use:
const product: Product = {
id: 1,
name: "Keyboard",
price: 1500
};
Type aliases and interfaces overlap for many object-shape use cases.
You will learn their differences as your TypeScript skills grow.
Union Types
A union type allows more than one type.
Example:
let id:
string | number;
id = 10;
id = "A10";
Both are allowed.
This is not:
id = true;
because boolean is not part of the union.
Why Union Types Are Useful
Real applications often have values with a small set of possible forms.
Example:
type Status =
"loading" |
"success" |
"error";
Now:
let status: Status =
"loading";
Later:
status = "success";
TypeScript can prevent:
status = "finished";
when "finished" is not part of the allowed type.
Literal Types
The previous example uses string literal types.
Another:
type UserRole =
"admin" |
"editor" |
"customer";
Use:
const role: UserRole =
"editor";
This can be clearer than accepting every possible string.
any Type
TypeScript includes:
any
Example:
let value: any = 10;
value = "Hello";
value = true;
any largely turns off type checking for that value.
It can be useful when migrating old code, but overusing it removes many of TypeScript’s benefits.
Do not solve every type error by changing the value to any.
unknown Type
unknown can represent an unknown value while requiring you to check it before using it unsafely.
Example:
let value: unknown =
"Hello";
Before using string methods:
if (
typeof value === "string"
) {
console.log(
value.toUpperCase()
);
}
unknown is often safer than any when the data type is genuinely uncertain.
JavaScript Runtime Checks Still Matter
TypeScript does not validate every value coming from outside your program automatically.
Suppose an API returns:
{
"price": "free"
}
Your TypeScript interface may say:
interface Product {
price: number;
}
But the server response exists at runtime.
Simply writing a TypeScript type does not magically convert or validate the external JSON.
Runtime validation may still be required.
Type Assertion Is Not Runtime Validation
You may see:
const product =
data as Product;
This tells TypeScript how you want the value treated.
It does not inspect the server data and prove that it matches Product.
If external data matters, validate the runtime structure.
This distinction is very important for API work.
TypeScript and null
TypeScript can help you handle missing values.
Example:
let selectedProduct:
Product | null =
null;
Now code must consider that selectedProduct may not contain a product yet.
Example:
if (selectedProduct) {
console.log(
selectedProduct.name
);
}
This makes nullable states explicit.
Optional Chaining Still Works
TypeScript uses the JavaScript optional chaining syntax you already learned.
Example:
const city =
user.address?.city;
This is still JavaScript syntax supported in TypeScript.
Type information can make the editor understand why the value may be missing.
Nullish Coalescing Still Works
Example:
const displayName =
user.name ??
"Guest";
JavaScript features such as:
?.
??
...
remain useful in TypeScript.
Classes in JavaScript
JavaScript class:
class Product {
constructor(
name,
price
) {
this.name =
name;
this.price =
price;
}
}
Create:
const product =
new Product(
"Keyboard",
1500
);
Classes in TypeScript
TypeScript can type the properties and constructor.
class Product {
name: string;
price: number;
constructor(
name: string,
price: number
) {
this.name =
name;
this.price =
price;
}
}
Now the class has a clearer data contract.
TypeScript Access Modifiers
TypeScript classes support modifiers such as:
public
private
protected
Example:
class UserService {
private apiUrl:
string =
"/api/users";
}
This helps describe how class members should be accessed in TypeScript code.
Angular services and classes use these concepts frequently.
public
A public member can be accessed from outside the class.
Example:
class Product {
public name: string;
constructor(
name: string
) {
this.name = name;
}
}
public is commonly the default accessibility in TypeScript classes.
private
Example:
class Account {
private balance:
number = 0;
deposit(
amount: number
): void {
this.balance +=
amount;
}
}
TypeScript prevents normal access to:
account.balance
from outside the class when balance is declared private.
Constructor Parameter Properties
TypeScript can shorten this:
class Product {
name: string;
price: number;
constructor(
name: string,
price: number
) {
this.name = name;
this.price = price;
}
}
into:
class Product {
constructor(
public name: string,
public price: number
) {}
}
The constructor parameters also create class properties.
You may see this style often in Angular code.
JavaScript Modules Still Matter
JavaScript:
export function add(
a,
b
) {
return a + b;
}
Import:
import {
add
} from "./math.js";
TypeScript uses the same modern module concepts.
Example:
export function add(
a: number,
b: number
): number {
return a + b;
}
Angular code contains many imports, so understanding JavaScript modules first is valuable.
Type-Only Imports
TypeScript can import types.
Example:
import type {
Product
} from "./product";
This tells TypeScript that the import is used only for type information.
You do not need to master this on your first TypeScript day, but you will see type imports in modern projects.
Generics
Generics let a type work with different data types while preserving useful type information.
Simple example:
function getFirst<T>(
items: T[]
): T | undefined {
return items[0];
}
Use with numbers:
const firstNumber =
getFirst([
10,
20,
30
]);
Use with strings:
const firstName =
getFirst([
"Riya",
"Amit"
]);
The same function works with different item types.
Why Generics Matter Before Angular
You do not need advanced generic programming before Angular.
But you should recognize syntax such as:
Array<Product>
or generic-looking framework types.
Angular and related TypeScript libraries use generics frequently.
Learn the basic idea:
A generic lets reusable code keep track of the type it is working with.
Typed Promises
JavaScript Promise:
function getProduct() {
return Promise.resolve({
name: "Keyboard"
});
}
TypeScript can describe the resolved value:
interface Product {
name: string;
}
function getProduct():
Promise<Product> {
return Promise.resolve({
name: "Keyboard"
});
}
Now TypeScript knows what:
await getProduct()
should return.
Async Function Return Type
Example:
async function getProduct():
Promise<Product> {
return {
name: "Keyboard"
};
}
An async function returns a Promise.
The generic type:
Promise<Product>
describes the fulfilled value.
Review JavaScript Promises and JavaScript Async/Await if that relationship is unclear.
Typed API Data
Suppose:
interface Product {
id: number;
name: string;
price: number;
}
You may create:
async function loadProducts():
Promise<Product[]> {
const response =
await fetch(
"/api/products"
);
if (!response.ok) {
throw new Error(
`HTTP ${response.status}`
);
}
return response.json();
}
The return type documents what your application expects.
However, remember:
The annotation does not prove the server returned valid Product objects.
Runtime validation can still be necessary.
TypeScript Catches Many Errors Earlier
JavaScript:
const product = {
name: "Keyboard",
price: 1500
};
console.log(
product.prcie
);
The misspelled property returns:
undefined
at runtime.
With a typed object, TypeScript can often report that:
prcie
does not exist on the expected type.
This kind of feedback is useful in large codebases.
Editor Autocomplete
Type information can improve editor suggestions.
If TypeScript knows:
const product:
Product
your editor can suggest properties such as:
id
name
price
This reduces the need to remember every object field.
It also helps during refactoring.
Safer Refactoring
Suppose you rename:
productName
to:
name
in a large application.
Type-aware tools can help find affected references.
TypeScript does not make refactoring risk-free, but stronger type information can reveal many broken usages earlier.
TypeScript Errors Do Not Replace Testing
This is valid TypeScript:
function calculateTotal(
price: number,
quantity: number
): number {
return price + quantity;
}
The types are correct.
The business logic is wrong if you wanted:
price × quantity
TypeScript cannot know every business requirement.
You still need:
- Testing
- Debugging
- Correct requirements
- Runtime validation
JavaScript Example With a Logic Bug
function calculateTotal(
price,
quantity
) {
return price + quantity;
}
Input:
500
3
Output:
503
TypeScript can ensure both values are numbers, but it cannot automatically know that multiplication was intended.
Does TypeScript Run Directly in the Browser?
Browsers execute JavaScript.
TypeScript-specific syntax such as:
const age: number = 25;
is normally processed by TypeScript-aware tooling and emitted as JavaScript.
The browser then runs the resulting JavaScript.
For example, TypeScript:
const age: number =
25;
can become JavaScript similar to:
const age =
25;
The type annotation does not exist as a normal runtime JavaScript feature.
TypeScript Compilation
The TypeScript compiler is commonly called:
tsc
It can:
- Check TypeScript types
- Transform TypeScript into JavaScript
- Follow project compiler settings
Modern frameworks and build tools may handle this process for you.
Understanding that TypeScript becomes JavaScript is more important than memorizing every compiler option at first.
.js vs .ts Files
JavaScript files commonly use:
.js
TypeScript files commonly use:
.ts
TypeScript files containing JSX may use:
.tsx
Angular application code commonly uses .ts files.
tsconfig.json
TypeScript projects commonly use:
tsconfig.json
This file configures TypeScript compiler behavior.
It can control things such as:
- Strictness
- Module settings
- JavaScript target
- Included files
- Output behavior
- Type-checking options
You do not need to memorize every tsconfig option before learning Angular.
Angular tooling normally creates and manages a suitable project setup.
strict Mode in TypeScript
TypeScript projects can enable stricter type checking.
Strict settings help identify more potentially unsafe code.
For example, they can make you handle values that might be:
null
undefined
This may feel slower at first, but it often catches mistakes early.
Do not disable type checking only to make errors disappear.
Understand what the type checker is warning about.
TypeScript Is Not Runtime Validation
This point deserves repeating.
Suppose your API returns:
{
"id": "wrong",
"name": 100
}
Your TypeScript code may expect:
interface User {
id: number;
name: string;
}
The server response still exists at runtime.
TypeScript types are removed during normal compilation.
If the API cannot be fully trusted, validate the runtime data.
TypeScript Is Not Security
Types can reduce programming mistakes.
They do not provide:
- Authentication
- Authorization
- Encryption
- Input sanitization
- Server validation
- XSS protection
- CSRF protection
- Database security
Do not treat a typed frontend as a secure frontend automatically.
Security still depends on your application architecture.
JavaScript and TypeScript With localStorage
localStorage returns strings.
TypeScript does not change that browser behavior.
Example:
const storedUser =
localStorage.getItem(
"user"
);
The value may be:
string
or:
null
Your TypeScript code should handle that possibility.
Example:
if (storedUser) {
const user =
JSON.parse(
storedUser
);
console.log(user);
}
Even after JSON.parse(), runtime validation may be useful for important stored data.
Review JavaScript localStorage.
JavaScript and TypeScript With Fetch
Fetch still works the same browser way.
JavaScript:
const response =
await fetch(
"/api/products"
);
TypeScript:
const response =
await fetch(
"/api/products"
);
The Fetch API is still a browser API.
TypeScript adds type checking around how your code uses the response and resulting data.
Review JavaScript Fetch API.
TypeScript Does Not Replace JavaScript Knowledge
You still need to understand why this works:
const availableProducts =
products.filter(
(product) =>
product.inStock
);
TypeScript may tell you:
product is a Product
But JavaScript knowledge tells you:
- What
filter()does - What the arrow function does
- What truthy values mean
- Why a new array is returned
TypeScript helps describe the code.
JavaScript knowledge helps you understand the code.
Why Angular Uses TypeScript
Angular development benefits from TypeScript features because Angular applications often have:
- Many components
- Services
- Structured models
- Dependency injection
- API data
- Forms
- Routing
- Shared modules and utilities
- Large teams
- Refactoring needs
Type information can make those relationships easier to understand and maintain.
Angular also provides framework tooling designed around TypeScript.
What TypeScript Adds Before Angular
Before Angular, focus on these TypeScript topics:
- Primitive type annotations
- Arrays
- Object types
- Interfaces
- Type aliases
- Optional properties
- Union types
- Literal types
- Function parameter types
- Function return types
- Classes
- Access modifiers
- Modules
- Generics basics
- Promise types
nullandundefined- Type narrowing
unknown- Basic type assertions
- Strict type checking
You do not need advanced TypeScript metaprogramming before your first Angular component.
Type Narrowing
Type narrowing means using runtime checks to reduce a broader type.
Example:
function printValue(
value:
string | number
): void {
if (
typeof value ===
"string"
) {
console.log(
value.toUpperCase()
);
return;
}
console.log(
value.toFixed(2)
);
}
Inside the first branch, TypeScript knows:
value is a string
Outside that branch, the remaining possibility is a number.
This is a powerful TypeScript concept.
Narrowing With in
Suppose:
type User =
{
name: string;
};
type Admin =
{
name: string;
permissions: string[];
};
You can check:
if (
"permissions" in account
) {
console.log(
account.permissions
);
}
TypeScript can use the runtime check to understand the narrower type.
Type Assertions
A type assertion looks like:
const input =
document.querySelector(
"#email"
) as HTMLInputElement;
This tells TypeScript to treat the result as an HTMLInputElement.
Be careful.
The assertion does not make the selected element exist.
If the selector returns null, an assertion does not create the element.
A safer pattern may still require a runtime check.
TypeScript and DOM Elements
Without additional narrowing:
const button =
document.querySelector(
"#button"
);
TypeScript knows the result may be:
Element | null
That is useful because querySelector() can actually return null.
You may write:
if (button) {
button.addEventListener(
"click",
() => {
console.log(
"Clicked"
);
}
);
}
The type checker encourages you to handle a real browser possibility.
TypeScript Cannot Make a Wrong Selector Correct
If your HTML uses:
<button id="buyButton">
and your TypeScript uses:
document.querySelector(
"#buy-button"
);
the selector still returns null.
Types help you handle the possibility.
They do not repair incorrect HTML or selectors.
Debugging still matters.
Review JavaScript Debugging.
JavaScript vs TypeScript Error Timing
Consider:
const user = {
name: "Riya"
};
console.log(
user.email.toLowerCase()
);
In JavaScript, the error appears when the line runs because user.email is undefined.
With a properly typed TypeScript object that does not include email, the editor or compiler can often flag the invalid property access before runtime.
This is one of TypeScript’s main benefits.
JavaScript vs TypeScript for Small Projects
For a very small one-page script, plain JavaScript may be enough.
Examples:
- Tiny interactive widget
- Simple landing-page behavior
- Short experiment
- Small learning exercise
TypeScript adds setup and type concepts that may not always be necessary for a tiny script.
JavaScript vs TypeScript for Larger Applications
TypeScript often becomes more valuable as an application grows.
It can help with:
- Shared data structures
- Larger teams
- API models
- Refactoring
- Editor navigation
- Function contracts
- Class relationships
- Reusable libraries
- Framework applications
Angular projects are a strong example of where TypeScript is deeply integrated into the development workflow.
Should Beginners Learn JavaScript or TypeScript First?
Learn JavaScript fundamentals first.
A useful path is:
HTML
↓
CSS
↓
JavaScript
↓
TypeScript
↓
Angular
You do not need to finish every advanced JavaScript topic.
You should understand the language features TypeScript builds on.
Review JavaScript Before Angular for the readiness checklist.
Can You Learn JavaScript and TypeScript Together?
After learning the JavaScript basics, yes.
For example, learn this JavaScript:
function greet(name) {
return `Hello ${name}`;
}
Then immediately see the TypeScript version:
function greet(
name: string
): string {
return `Hello ${name}`;
}
Side-by-side practice makes the transition easier.
JavaScript to TypeScript: Simple Conversion
JavaScript
const product = {
id: 1,
name: "Keyboard",
price: 1500
};
function calculateTotal(
product,
quantity
) {
return (
product.price *
quantity
);
}
TypeScript
interface Product {
id: number;
name: string;
price: number;
}
const product: Product = {
id: 1,
name: "Keyboard",
price: 1500
};
function calculateTotal(
product: Product,
quantity: number
): number {
return (
product.price *
quantity
);
}
The core logic is still JavaScript.
TypeScript adds the type contract.
JavaScript Array Method vs Typed Array Method
JavaScript:
const products = [
{
id: 1,
name: "Keyboard"
},
{
id: 2,
name: "Mouse"
}
];
const product =
products.find(
(item) =>
item.id === 2
);
TypeScript:
interface Product {
id: number;
name: string;
}
const products:
Product[] = [
{
id: 1,
name: "Keyboard"
},
{
id: 2,
name: "Mouse"
}
];
const product =
products.find(
(item) =>
item.id === 2
);
TypeScript knows that each item is a Product.
It can offer stronger autocomplete and property checking.
JavaScript API Function vs TypeScript API Function
JavaScript:
async function loadProducts() {
const response =
await fetch(
"/api/products"
);
return response.json();
}
TypeScript:
interface Product {
id: number;
name: string;
price: number;
}
async function loadProducts():
Promise<Product[]> {
const response =
await fetch(
"/api/products"
);
if (!response.ok) {
throw new Error(
`HTTP ${response.status}`
);
}
return response.json();
}
The TypeScript return type documents what the function expects to provide.
But runtime API validation is still separate.
TypeScript and Angular Example
An Angular class may look conceptually like:
export class ProductList {
products:
Product[] = [];
selectedProduct:
Product | null =
null;
selectProduct(
product: Product
): void {
this.selectedProduct =
product;
}
}
The JavaScript ideas are still visible:
- Class
- Property
- Array
- Object
- Function parameter
- Assignment
this
TypeScript adds:
Product[]Product | nullproduct: Product: void
This is why JavaScript fundamentals make Angular code easier to read.
JavaScript vs TypeScript: Advantages of JavaScript
JavaScript is:
- Native to browsers
- Essential for web development
- Simple to begin using
- Flexible
- Supported by a huge ecosystem
- The foundation TypeScript builds on
Every TypeScript developer still needs JavaScript knowledge.
JavaScript vs TypeScript: Advantages of TypeScript
TypeScript can provide:
- Static type checking
- Typed function contracts
- Typed object structures
- Interfaces
- Union and literal types
- Generics
- Strong editor support
- Safer large-scale refactoring
- Earlier detection of many mistakes
- Better documentation through types
These benefits become more noticeable as projects grow.
Possible Costs of TypeScript
TypeScript also adds:
- Type syntax to learn
- Build or transformation tooling
- Compiler configuration
- Type errors to resolve
- Additional concepts such as generics and narrowing
For large frontend projects, these costs can be worthwhile.
For a tiny script, plain JavaScript may remain simpler.
TypeScript Does Not Make Bad Code Good
This can be typed:
function calculateDiscount(
price: number
): number {
return price + 500;
}
If the requirement was to subtract a discount, the function is still wrong.
Types improve correctness in specific ways.
They do not replace good architecture, testing, debugging, or careful logic.
Common Beginner Mistakes
Starting TypeScript Before Understanding JavaScript Functions
If parameters, returns, callbacks, and scope are unclear, adding types can make the code more confusing.
Learn the JavaScript behavior first.
Adding Types Everywhere Without Need
This is valid:
const name: string =
"Riya";
But TypeScript can infer the type.
Often this is enough:
const name =
"Riya";
Use explicit annotations where they add useful information.
Using any to Remove Every Error
Avoid:
let data: any;
only because the correct type takes effort.
Overusing any removes TypeScript’s protection.
Thinking a Type Assertion Validates Data
This:
data as Product
does not prove that data is a valid product.
Assuming Interfaces Exist at Runtime
Interfaces help the TypeScript type checker.
They are not runtime JavaScript objects that can validate API responses.
Ignoring null
DOM selectors and API data can be missing.
Do not remove null safety only to silence the compiler.
Treating TypeScript Errors as Annoying Obstacles
A type error often points to a real mismatch in your assumptions.
Read it before changing the type.
Confusing Type Errors With Runtime Errors
TypeScript can catch many problems before execution.
Runtime errors can still happen from:
- Bad API data
- Missing DOM elements
- Network failure
- Incorrect logic
- Browser behavior
Skipping Runtime Validation
External data can be wrong even when your local TypeScript types are correct.
Learning Angular Syntax Without Learning TypeScript Basics
Angular becomes easier when interfaces, classes, union types, modules, and typed functions already make sense.
Best Practices When Moving From JavaScript to TypeScript
Keep using your JavaScript knowledge.
Add TypeScript gradually.
Start with:
- Function parameters
- Function returns
- Arrays
- Object types
- Interfaces
Let TypeScript infer obvious local values.
Avoid unnecessary any.
Use unknown when a value truly has an unknown type and needs checking.
Handle null and undefined instead of hiding them.
Learn type narrowing.
Understand interfaces and type aliases.
Practice classes and access modifiers.
Learn basic generics after the core types feel comfortable.
Remember that API data still needs runtime validation.
Keep debugging and testing your runtime JavaScript behavior.
Beginner Exercise
Convert this JavaScript into TypeScript:
const product = {
id: 1,
name: "Keyboard",
price: 1500,
inStock: true
};
function calculateTotal(
product,
quantity
) {
return (
product.price *
quantity
);
}
Requirements:
- Create a
Productinterface. - Type
idas a number. - Type
nameas a string. - Type
priceas a number. - Type
inStockas a boolean. - Type the
productparameter. - Type
quantityas a number. - Set the function return type to number.
- Call the function with quantity
2. - Confirm the result is
3000.
Then intentionally call:
calculateTotal(
product,
"2"
);
Read the TypeScript error.
Challenge Exercise
Convert this JavaScript data:
const users = [
{
id: 1,
name: "Riya",
role: "admin"
},
{
id: 2,
name: "Amit",
role: "editor"
}
];
Create:
type UserRole =
"admin" |
"editor" |
"customer";
Then create a User interface.
Requirements:
idis a number.nameis a string.roleusesUserRole.- Type the users array.
- Use
find()to get user ID2. - Create a function that accepts a
User. - Return a string containing the user’s name and role.
Extra Challenge
Create:
interface Product {
id: number;
name: string;
price: number;
}
Then write:
async function loadProducts():
Promise<Product[]> {
// your code
}
Use fetch() and async/await.
Check response.ok.
Return the parsed JSON.
Then answer this question:
Does
Promiseprove that the server returned valid Product objects?
The correct answer is no.
Add a simple runtime check for at least one important field before your application relies on the data.
Frequently Asked Questions
What is the difference between JavaScript and TypeScript?
JavaScript is a programming language used directly by browsers and other JavaScript runtimes.
TypeScript builds on JavaScript and adds a static type system and development-time language features.
Is TypeScript a replacement for JavaScript?
No.
TypeScript builds on JavaScript and is normally transformed into JavaScript for execution.
You still need JavaScript knowledge.
Does TypeScript run directly in browsers?
Browsers execute JavaScript.
TypeScript-specific syntax is normally processed by TypeScript-aware tooling and emitted as JavaScript before the browser runs it.
Should I learn JavaScript or TypeScript first?
Learn JavaScript fundamentals first.
Then add TypeScript.
Can I learn TypeScript without JavaScript?
You can read TypeScript syntax, but learning it without JavaScript fundamentals usually makes understanding runtime behavior much harder.
Is TypeScript harder than JavaScript?
TypeScript adds new concepts such as static types, interfaces, generics, unions, and type narrowing.
Once JavaScript fundamentals are clear, these additions are much easier to learn.
Is JavaScript dynamically typed?
Yes.
JavaScript values are typed at runtime, and variables can hold values of different types over time.
Is TypeScript statically typed?
TypeScript adds static type checking during development.
Its type information is normally removed when code is emitted as JavaScript.
What is type inference in TypeScript?
Type inference means TypeScript can often determine a value’s type without an explicit annotation.
Example:
const name = "Riya";
TypeScript can infer a string type.
What is an interface in TypeScript?
An interface can describe the expected shape of an object.
Example:
interface User {
id: number;
name: string;
}
What is a type alias?
A type alias creates a name for a type.
Example:
type UserId =
string | number;
What is a union type?
A union allows more than one type.
let id:
string | number;
What is a literal type?
A literal type limits a value to specific literal choices.
type Status =
"loading" |
"success" |
"error";
What is any in TypeScript?
any allows almost any operation and largely disables type checking for that value.
Avoid using it as the default solution to type problems.
What is unknown in TypeScript?
unknown represents a value whose type is not yet known.
Unlike any, TypeScript requires you to narrow or check it before unsafe operations.
What is type narrowing?
Type narrowing uses checks such as typeof, property tests, or control flow to reduce a broad type into a more specific type.
What is a generic in TypeScript?
A generic lets reusable code work with different types while preserving information about those types.
What does Promise mean?
It describes a Promise expected to fulfill with an array of Product values.
It does not automatically validate external runtime JSON.
Do TypeScript interfaces validate API responses?
No.
Interfaces are development-time type information.
External API data may still need runtime validation.
What is a type assertion?
A type assertion tells TypeScript how you want a value treated.
It does not perform runtime validation.
Does TypeScript prevent all bugs?
No.
TypeScript can catch many type-related mistakes.
It cannot automatically catch every logic, runtime, API, security, or business-rule error.
Does TypeScript improve editor autocomplete?
Often, yes.
Type information can give editors more knowledge about available properties, function parameters, and return values.
Is TypeScript required for Angular?
Angular’s standard development workflow is TypeScript-based, so TypeScript knowledge is important for Angular development.
How much TypeScript should I learn before Angular?
Learn the fundamentals:
- Primitive types
- Arrays
- Object types
- Interfaces
- Type aliases
- Union types
- Functions
- Classes
- Access modifiers
- Modules
- Generics basics
- Promise types
- Null handling
- Type narrowing
You can deepen the advanced topics while learning Angular.
Should I learn TypeScript before Angular or together with Angular?
Learn the TypeScript fundamentals first, then continue improving TypeScript while you learn Angular.
This keeps your first Angular lessons focused on framework concepts instead of basic type syntax.
Is TypeScript useful outside Angular?
Yes.
TypeScript is used across many JavaScript environments, including frontend applications, Node.js projects, libraries, and other frameworks.
What should I learn after JavaScript vs TypeScript?
Move into a focused TypeScript tutorial for JavaScript developers.
Start by typing variables, functions, arrays, and objects before moving into interfaces, unions, classes, generics, modules, and typed asynchronous code.
Summary
JavaScript and TypeScript are closely connected.
JavaScript gives you the language and runtime behavior.
TypeScript adds a type system that can check many mistakes during development.
JavaScript:
function add(a, b) {
return a + b;
}
TypeScript:
function add(
a: number,
b: number
): number {
return a + b;
}
The main TypeScript additions you learned include:
- Type annotations
- Type inference
- Typed parameters
- Return types
- Typed arrays
- Interfaces
- Type aliases
- Optional properties
readonly- Union types
- Literal types
anyunknown- Type narrowing
- Classes
- Access modifiers
- Generics
- Typed Promises
- Type assertions
- Null handling
You also learned an important limitation:
TypeScript types do not automatically validate runtime data.
APIs, localStorage, user input, and other external values still need appropriate runtime checks.
A useful learning path is:
JavaScript
↓
TypeScript
↓
Angular
You already have the JavaScript foundation.
The next step is learning how to apply TypeScript types to the JavaScript patterns you already know.
Continue Learning
Previous Lesson: JavaScript Before Angular: What You Should Know First
Course Home: JavaScript Tutorial for Beginners
Next Lesson: TypeScript for JavaScript Developers
In the next lesson, you will start writing TypeScript directly by adding types to variables, functions, arrays, objects, interfaces, unions, and everyday JavaScript code.
