Type vs Interface in TypeScript: Complete Guide with Examples (Beginner to Advanced)

When working with TypeScript, one of the most common questions is:

πŸ€” Should I use type or interface?

Both are used to define the structure of data, but they behave differently in certain scenarios.

In this guide, you’ll learn:

  • What type and interface are
  • Key differences
  • All important scenarios with examples
  • When to use each (very important)

What is interface in TypeScript?

An interface is used to define the structure (shape) of an object.


Basic Example

interface User {
name: string;
age: number;
}
const user: User = {
name: "Raju",
age: 25,
};

What is type in TypeScript?

A type is more flexible and can define:

  • Objects
  • Primitives
  • Unions
  • Tuples
  • Functions

Basic Example

type User = {
name: string;
age: number;
};

πŸ‘‰ Works similar to interface for objects


Key Differences (Quick Overview)

Featureinterfacetype
Object structureβœ… Yesβœ… Yes
Union types❌ Noβœ… Yes
Intersection types⚠️ Limitedβœ… Yes
Declaration mergingβœ… Yes❌ No
FlexibilityMediumHigh

Scenario 1: Object Definition

πŸ‘‰ Both work the same

interface User {
name: string;
}
type User = {
name: string;
};

βœ… No major difference here


Scenario 2: Declaration Merging (Important)

βœ… interface supports merging

interface User {
name: string;
}

interface User {
age: number;
}

πŸ‘‰ Result:

{
name: string;
age: number;
}

❌ type does NOT support merging

type User = {
name: string;
};

type User = {
age: number;
}; // ❌ Error

Scenario 3: Union Types

βœ… Using type

type Status = "success" | "error" | "loading";

❌ interface cannot do this

πŸ‘‰ Not supported


Scenario 4: Intersection Types

βœ… Using type

type Person = {
name: string;
};

type Employee = Person & {
salary: number;
};

⚠️ interface alternative

interface Person {
name: string;
}

interface Employee extends Person {
salary: number;
}

Scenario 5: Functions

βœ… Using type

type Add = (a: number, b: number) => number;

βœ… Using interface

interface Add {
(a: number, b: number): number;
}

Scenario 6: Extending / Inheritance

interface

interface Person {
name: string;
}

interface Employee extends Person {
salary: number;
}

type

type Person = {
name: string;
};

type Employee = Person & {
salary: number;
};

Scenario 7: Primitive Types

βœ… Only type supports this

type ID = string | number;

πŸ‘‰ interface cannot do this ❌


Scenario 8: Tuples

type Point = [number, number];

πŸ‘‰ Only type supports tuples


Scenario 9: Working with Classes

interface (preferred)

interface User {
name: string;
}

class Person implements User {
name = "Raju";
}

When to Use interface

Use interface when:

  • Defining object structure
  • Working with classes
  • Need declaration merging
  • Building large applications

When to Use type

Use type when:

  • Using unions (|)
  • Using intersections (&)
  • Working with primitives
  • Advanced type logic

Best Practice (Very Important)

πŸ‘‰ Use both together:

type Status = "success" | "error";

interface ApiResponse {
status: Status;
data: string;
}

Common Mistakes


❌ Using interface for unions

interface Status = "success" | "error"; // ❌

❌ Overusing any

πŸ‘‰ Avoid losing type safety


❌ Confusion between both

πŸ‘‰ Use based on use case


Interview Tip

If asked:

β€œtype vs interface?”

πŸ‘‰ Answer:

β€œBoth define data shapes, but type is more flexible (supports unions, tuples), while interface supports declaration merging and is better for object-oriented design.”


Final Summary

  • Both define structure of data
  • interface β†’ best for objects & classes
  • type β†’ best for advanced types
  • Use both based on need

πŸ’‘ Found this helpful? Subscribe to get simple TypeScript tutorials, interview questions, and real-world coding tips. Happy Coding!

TypeScript Error: β€œObject literal may only specify known properties” (Fix Explained)

While working with TypeScript, you might encounter this error:

Object literal may only specify known properties, and 'age' does not exist in type 'User'

This error can be confusing for beginners.

In this guide, you’ll learn:

  • What this error means
  • Why it happens
  • How to fix it (step-by-step)
  • Common mistakes to avoid

What Does This Error Mean?

πŸ‘‰ In simple terms:

TypeScript is telling you that you are adding a property that is not defined in the type or interface


Example That Causes the Error

interface User {
name: string;
}

const user: User = {
name: "Raju",
age: 25, // ❌ Error here
};

πŸ‘‰ Error:

Object literal may only specify known properties, and 'age' does not exist in type 'User'

Why This Error Happens

TypeScript uses strict type checking.

πŸ‘‰ It ensures that:

  • You only use properties defined in the type
  • No extra or unexpected data is added

How to Fix This Error


Fix 1: Add the Missing Property

If the property is valid, add it to the interface:

interface User {
name: string;
age: number;
}

πŸ‘‰ Now it works βœ…


Fix 2: Remove Extra Property

If the property is not needed:

const user: User = {
name: "Raju",
};

Fix 3: Use Index Signature (Flexible Objects)

If object can have dynamic properties:

interface User {
name: string;
[key: string]: any;
}

πŸ‘‰ Allows extra properties βœ…


Fix 4: Use Type Assertion (Use Carefully)

const user = {
name: "Raju",
age: 25,
} as User;

⚠️ This tells TypeScript to ignore extra properties
πŸ‘‰ Use only when you are sure


Fix 5: Assign Object to Variable First

const temp = {
name: "Raju",
age: 25,
};

const user: User = temp;

πŸ‘‰ This may bypass strict checking in some cases


⚠️ Common Mistakes


❌ Typo in property name

namee: "Raju" // ❌ wrong

❌ Forgetting to update interface

πŸ‘‰ Adding new fields but not updating type


❌ Overusing any

πŸ‘‰ Removes TypeScript benefits


Real-World Scenario

Imagine:

πŸ‘‰ API returns:

{
"name": "Raju",
"age": 25
}

But your interface is:

interface User {
name: string;
}

πŸ‘‰ You’ll get this error


Best Practices

  • Keep types updated
  • Avoid unnecessary properties
  • Use strict typing
  • Avoid overusing any

Interview Tip

If asked:

β€œWhat is this error?”

πŸ‘‰ Answer:

β€œIt occurs when an object contains properties that are not defined in its type or interface.”


Final Summary

  • TypeScript enforces strict object structure
  • Extra properties cause this error
  • Fix by updating type or removing extra fields
  • Use index signature for flexible objects

Related Articles


πŸ’‘ Facing more TypeScript errors? Subscribe to get simple fixes, real-world examples, and developer-friendly explanations. Happy Coding!

What is DOM, Virtual DOM, and Real DOM in React? (Simple Explanation for Beginners)

If you are new to web development or React, you might have heard terms like:

  • DOM
  • Virtual DOM
  • Real DOM

And it can feel confusing πŸ˜…

Don’t worry β€” in this guide, we’ll explain everything in very simple terms, even if you are not from a technical background.


What is DOM?

DOM stands for:

Document Object Model

πŸ‘‰ In simple words:

DOM is a structure of your web page


Real-Life Analogy

Think of a web page like a house 🏠

  • Walls β†’ HTML elements
  • Furniture β†’ Content
  • Layout β†’ Structure

πŸ‘‰ DOM is like the blueprint of the house


Example

<h1>Hello</h1>
<p>Welcome to my website</p>

πŸ‘‰ Browser converts this into a structure like:

Page
β”œβ”€β”€ h1 β†’ "Hello"
└── p β†’ "Welcome to my website"

What is Real DOM?

Real DOM is:

The actual DOM in the browser


Problem with Real DOM

Whenever something changes:

πŸ‘‰ The browser may rebuild or update large parts of the page

This can be:

  • Slow
  • Inefficient
  • Costly for performance

Example

Imagine:

πŸ‘‰ You change one word on the page

❌ Browser may re-check or update entire section


What is Virtual DOM?

Virtual DOM is a concept used by React


Simple Definition

Virtual DOM is a lightweight copy of the Real DOM


Real-Life Analogy

Think like this:

πŸ‘‰ Instead of directly editing your house 🏠
πŸ‘‰ You first make changes in a model (mini version)

Then:

βœ” Compare changes
βœ” Update only what is needed


How Virtual DOM Works (Step-by-Step)


Step 1: Initial Render

React creates:
πŸ‘‰ Virtual DOM
πŸ‘‰ Real DOM


Step 2: State Changes

When something changes:

πŸ‘‰ React creates a new Virtual DOM


Step 3: Comparison (Diffing)

React compares:

  • Old Virtual DOM
  • New Virtual DOM

Step 4: Update Only Changes

πŸ‘‰ React updates only the changed parts in Real DOM


Example (Very Simple)


Initial UI

<h1>Hello</h1>

Updated UI

<h1>Hello World</h1>

What React Does

❌ Does NOT reload whole page
βœ… Updates only text inside <h1>


Why Virtual DOM is Faster

FeatureReal DOMVirtual DOM
UpdatesFull or largeOnly required parts
SpeedSlowerFaster
EfficiencyLowHigh

Key Differences (Simple Table)

FeatureReal DOMVirtual DOM
TypeActual UICopy of UI
SpeedSlowFast
UpdatesDirectIndirect
Used byBrowserReact

Why React Uses Virtual DOM

React uses Virtual DOM to:

βœ” Improve performance
βœ” Reduce unnecessary updates
βœ” Make apps faster


Real-World Example

Imagine a shopping app:

πŸ‘‰ You add 1 item

❌ Without Virtual DOM β†’ entire page refresh
βœ… With Virtual DOM β†’ only cart updates


Common Misunderstanding


❌ Virtual DOM replaces Real DOM

πŸ‘‰ Not true

πŸ‘‰ It works along with Real DOM


Interview Tip

If asked:

β€œWhat is Virtual DOM?”

πŸ‘‰ Answer:

β€œIt is a lightweight copy of the Real DOM used by React to efficiently update only changed parts of the UI.”


Final Summary

  • DOM = structure of webpage
  • Real DOM = actual browser DOM
  • Virtual DOM = lightweight copy used by React
  • React updates only changed parts β†’ faster performance

πŸ’‘ Found this helpful? Subscribe to get simple explanations of complex concepts, React tutorials, and coding tips. Happy Coding!

What is React JS? Why is it Efficient? (Beginner-Friendly Guide)

If you are starting frontend development, one of the most popular technologies you’ll hear about is React JS.

But many beginners ask:

πŸ€” What exactly is React?
πŸ€” Why do companies prefer React over other frameworks?

In this guide, you’ll learn:

  • What React JS is
  • How it works
  • Why it is efficient
  • Real-world examples

What is React JS?

React is a JavaScript library used to build user interfaces (UI), especially for web applications.

πŸ‘‰ It was developed by Meta (formerly Facebook).


Simple Definition

React is a library that helps you build fast, interactive, and reusable UI components.


Example of React Code

function App() {
return <h1>Hello, World!</h1>;
}

πŸ‘‰ This renders a heading on the screen.


How React Works

React uses a component-based architecture.


What are Components?

Components are small reusable pieces of UI.

Example:

  • Header
  • Footer
  • Button
  • Form

Example

function Button() {
return <button>Click Me</button>;
}

πŸ‘‰ You can reuse this anywhere in your app.


Why is React Efficient?

This is the most important question πŸ‘‡


1. Virtual DOM (Main Reason)

React uses something called the Virtual DOM.


What is DOM?

DOM = Document Object Model
πŸ‘‰ Represents your webpage structure


Problem with Normal DOM

  • Slow updates
  • Entire UI re-renders

React Solution: Virtual DOM

React creates a lightweight copy of the DOM.

πŸ‘‰ When data changes:

  • React compares old vs new (diffing)
  • Updates only changed parts

Result:

βœ” Faster updates
βœ” Better performance


2. Reusable Components

Instead of writing code again and again:

<Button />
<Button />
<Button />

πŸ‘‰ One component β†’ multiple uses


3. Efficient Rendering

React updates only what is needed:

❌ Not entire page
βœ… Only changed components


4. One-Way Data Flow

React uses unidirectional data flow:

πŸ‘‰ Parent β†’ Child

Benefits:

  • Easy debugging
  • Predictable behavior

5. Declarative Approach

Instead of telling β€œhow to update UI”:

πŸ‘‰ You describe β€œwhat UI should look like”

Example:

const isLoggedIn = true;return isLoggedIn ? <Dashboard /> : <Login />;

6. Strong Ecosystem

React has:

  • Huge community
  • Many libraries
  • Easy integrations

Real-World Example

Imagine a shopping app:

πŸ‘‰ When you add an item:

  • Only cart updates
  • Not entire page

πŸ‘‰ This is React efficiency πŸš€


React vs Traditional Approach

FeatureTraditional JSReact
UpdatesFull pagePartial
Code reuseLowHigh
PerformanceSlowerFaster

Common Misconceptions


❌ React is a Framework

πŸ‘‰ It’s actually a library


❌ React is only for big apps

πŸ‘‰ You can use it for small apps too


When to Use React?

Use React when:

  • Building dynamic UI
  • Creating large applications
  • Need reusable components

Interview Tip

If asked:

β€œWhy is React efficient?”

πŸ‘‰ Answer:

β€œBecause it uses Virtual DOM, updates only required parts, and uses reusable components.”


Final Summary

  • React is a UI library
  • Uses components
  • Virtual DOM improves performance
  • Efficient rendering saves time

πŸ‘‰ That’s why React is widely used πŸš€

πŸ’‘ Found this helpful? Subscribe to get simple React tutorials, interview questions, and real-world examples. Happy Coding!

rem vs px in CSS: What’s the Difference and When to Use Each?

When working with CSS, you often see units like px and rem.
But many developers get confused:

πŸ€” Should I use px or rem?

In this guide, you’ll learn:

  • What px and rem are
  • Key differences
  • Real-world use cases
  • When to use each (very important)

What is px in CSS?

px stands for pixels.

πŸ‘‰ It is a fixed unit, meaning it does not change based on screen size or user settings.


Example

h1 {
font-size: 16px;
}

πŸ‘‰ The font size will always be 16 pixels


What is rem in CSS?

rem stands for root em.

πŸ‘‰ It is a relative unit, based on the root (html) font size.


Example

html {
font-size: 16px;
}h1 {
font-size: 1rem;
}

πŸ‘‰ 1rem = 16px


How rem Works

If:

html {
font-size: 16px;
}

Then:

rempx
1rem16px
2rem32px
0.5rem8px

Key Differences Between rem and px

Featurepxrem
TypeFixedRelative
Responsive❌ Noβœ… Yes
Based onScreen pixelsRoot font size
Accessibility❌ Poorβœ… Better
ScalingNoYes

Why rem is Preferred in Modern CSS


πŸ”Ή 1. Better Responsiveness

If root font size changes:

html {
font-size: 18px;
}

πŸ‘‰ All rem values scale automatically


πŸ”Ή 2. Accessibility Support

Users can change browser font size β†’ rem adjusts automatically

πŸ‘‰ Helps users with vision issues πŸ‘


πŸ”Ή 3. Consistent Design

You can control entire UI from one place (html)


When to Use px

Use px when you need precise control:

  • Borders
  • Shadows
  • Icons (fixed size)
  • Hairline elements

Example

border: 1px solid black;

When to Use rem

Use rem for:

  • Font sizes
  • Spacing (margin, padding)
  • Layout scaling

Example

p {
font-size: 1rem;
margin: 1.5rem;
}

Real-World Example


❌ Using px (Not Flexible)

.container {
padding: 20px;
}

βœ… Using rem (Flexible)

.container {
padding: 1.25rem;
}

πŸ‘‰ Automatically adjusts with root font size


Common Mistakes


❌ Mixing units randomly

πŸ‘‰ Keep consistency


❌ Setting root font size incorrectly

html {
font-size: 10px;
}

πŸ‘‰ Use carefully


rem vs em (Quick Note)

  • rem β†’ based on root
  • em β†’ based on parent

πŸ‘‰ rem is easier to manage


Best Practice

πŸ‘‰ Use both together:

  • rem β†’ layout & typography
  • px β†’ borders & fine details

Real-World Use Cases

  • Responsive websites
  • Design systems
  • UI frameworks (like MUI)
  • Accessibility-friendly apps

Interview Tip

If asked:

β€œpx vs rem?”

πŸ‘‰ Answer:

β€œpx is fixed, while rem is relative to the root font size, making it more responsive and accessible.”


🏁 Final Summary

  • px = fixed unit
  • rem = scalable unit
  • Use rem for responsiveness
  • Use px for precision

πŸ‘‰ Modern CSS prefers rem


Related Articles

πŸ‘‰ Add these:


πŸ’‘ Found this helpful? Subscribe to get simple CSS guides, real-world examples, and frontend tips. Happy Coding!