DEV Community

Cover image for React TypeScript vs JavaScript - When to use which one (With Comprehensive Code Examples)
Sarthak Niranjan for CodeParrot

Posted on • Originally published at codeparrot.ai

React TypeScript vs JavaScript - When to use which one (With Comprehensive Code Examples)

Introduction:

In the world of React development, the debate of React TypeScript vs JavaScript is more than just a passing discussion—it's crucial. Choosing between these two languages can significantly impact your project's success. This guide will not only explore the differences but also delve into the benefits and specific use cases for both TypeScript and JavaScript in React applications. By understanding the nuances of React TypeScript vs JavaScript, you'll be better equipped to make an informed decision tailored to your development needs.

React TypeScript vs JavaScript Image

What is TypeScript?

TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. It adds optional static typing, classes, and modules to JavaScript, enhancing the development experience and catching errors early in the development process. Understanding React TypeScript vs JavaScript can help in choosing the right tool for your project needs.

Here's a simple example of TypeScript in action:

function greet(name: string): string {
  return `Hello, ${name}!`;
} 

console.log(greet("TypeScript")); // Output: Hello, TypeScript!
console.log(greet(123)); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
Enter fullscreen mode Exit fullscreen mode

Getting Started in React with TypeScript

To start a new React project with TypeScript, you can use Create React App with the TypeScript template. This setup aligns with the React TypeScript vs JavaScript debate by providing a ready-made TypeScript configuration for your project:

npx create-react-app my-typescript-app --template typescript
Enter fullscreen mode Exit fullscreen mode

This sets up a React project with TypeScript configuration out of the box.

Let’s create a simple React component using TypeScript:

import React from 'react';

interface GreetingProps {
  name: string;
}

const Greeting: React.FC<GreetingProps> = ({ name }) => {
  return <h1>Hello, {name}!</h1>;
};

export default Greeting;
Enter fullscreen mode Exit fullscreen mode

For more detailed documentation and examples, visit Using TypeScript – React

What is tsconfig.json?

The tsconfig.json file is crucial for TypeScript projects, especially when considering React TypeScript vs JavaScript. It specifies the root files and compiler options for the TypeScript compiler.

Here’s a basic tsconfig.json for a React project:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"]
}
Enter fullscreen mode Exit fullscreen mode

This configuration enables strict type-checking and sets up the compiler for React development.

The Toolkit (Extensions)

TypeScript shines when it comes to tooling. Popular extensions for VS Code, such as ESLint and Prettier, enhance the development experience in the context of React TypeScript vs JavaScript. For example:

1. ESLint: For linting TypeScript code.
Before ESLint:

const greet = (name: string) => {
  const message = `Hello, ${name}!`; // `message` is declared but never used
};

greet("Alice");
Enter fullscreen mode Exit fullscreen mode

After ESLint:

const greet = (name: string) => {
  console.log(`Hello, ${name}!`); // ESLint warns about the unused variable and suggests removing it
};

greet("Alice");
Enter fullscreen mode Exit fullscreen mode

2. Prettier: For formatting code.
Before Prettier:

const user = {name:"John", age:25,location:"New York"}; console.log(user);
Enter fullscreen mode Exit fullscreen mode

After Prettier:

const user = {
  name: "John",
  age: 25,
  location: "New York",
};

console.log(user);
Enter fullscreen mode Exit fullscreen mode

3. TypeScript Hero: For organizing imports.
Before TypeScript Hero:

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

// `User` is not imported, leading to an error.
Enter fullscreen mode Exit fullscreen mode

After TypeScript Hero:

import { User } from "./models/User"; // TypeScript Hero automatically adds the missing import.

const user: User = {
  name: "John",
  age: 25,
};
Enter fullscreen mode Exit fullscreen mode

TypeScript vs JavaScript

A) Differences in Learning Curve
TypeScript introduces additional concepts that developers need to learn:

  1. Type annotations
  2. Interfaces and type aliases
  3. Generics
  4. Union and intersection types

While these concepts take time to master, they provide powerful tools for creating robust and maintainable code.

Here's an example of how TypeScript can improve code clarity:

//JavaScript
function calculateTotal(items) {
  return items.reduce((total, item) => total + item.price * item.quantity, 0);
}


// TypeScript
interface Item {
  price: number;
  quantity: number;
}


function calculateTotal(items: Item[]): number {
  return items.reduce((total, item) => total + item.price * item.quantity, 0);
}
Enter fullscreen mode Exit fullscreen mode

The TypeScript version clearly defines the shape of the items array and the return type, making the function's purpose and usage more evident.

B) Maintainability (with examples)
TypeScript improves maintainability by catching errors early and making code more self-documenting.

Consider this example of a React component:

// JavaScript
const UserProfile = ({ user }) => {
  return (
    <div>
      <h2>{user.name}</h2>
      <p>Email: {user.email}</p>
      <p>Age: {user.age}</p>
    </div>
  );
};


// TypeScript
interface User {
  name: string;
  email: string;
  age: number;
}


const UserProfile: React.FC<{ user: User }> = ({ user }) => {
  return (
    <div>
      <h2>{user.name}</h2>
      <p>Email: {user.email}</p>
      <p>Age: {user.age}</p>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

The TypeScript version ensures that the user prop has the correct structure, preventing runtime errors and making the component's requirements clear.

C) Performance
In terms of runtime performance, TypeScript and JavaScript are essentially the same since TypeScript compiles to JavaScript. However, TypeScript can lead to performance improvements in development by:

  1. Catching errors earlier in the development process
  2. Enabling better code optimization through static analysis
  3. Improving code navigation and refactoring speed

Here's an example of how TypeScript can help prevent performance issues:

// JavaScript
function processLargeArray(arr) {
  return arr.map(item => item * 2);
}


// TypeScript
function processLargeArray(arr: number[]): number[] {
  return arr.map(item => item * 2);
}


// Usage
const numbers: number[] = [1, 2, 3, 4, 5];
const result = processLargeArray(numbers);


// TypeScript will catch this error at compile-time
const strings: string[] = ["1", "2", "3"];
processLargeArray(strings); // Error: Argument of type 'string[]' is not assignable to parameter of type 'number[]'.
Enter fullscreen mode Exit fullscreen mode

Conclusion: TypeScript vs JavaScript

When to Use JavaScript in React:

1. Rapid Prototyping and MVPs: Ideal for quickly validating ideas or building MVPs where time-to-market is crucial, and you can't afford the setup time of TypeScript.
2. Small-Scale or Short-Term Projects: Suitable for simple applications with limited scope or projects with a short lifespan that won't require long-term maintenance.
3. Team Familiarity and Tight Timelines: Best for teams experienced with JavaScript, especially when there's no time to learn TypeScript or when facing extremely tight deadlines.
4. Integration and Client Preferences: Useful when working with JavaScript-only libraries, or if clients prefer consistency with their existing JavaScript codebase.

When to Use TypeScript in React:

1. Large-Scale and Long-Term Projects: Ideal for complex, scalable applications that require maintainability over time, where code readability and type safety are crucial.
2. Team Collaboration and Code Maintenance: Great for larger or distributed teams where clear type definitions improve communication, and static typing aids in safer refactoring.
3. Complex Data and API Integration: Essential when dealing with complex data structures or external APIs, ensuring type safety and catching errors early.
4. Enhanced Developer Experience: Preferred for leveraging advanced IDE features, robust development environments, and type-safe state management in performance-critical applications.

Here's a simple decision-making helper:

interface ProjectFactor {
  name: string;
  weight: number;
  scoreForTypeScript: number;
  scoreForJavaScript: number;
}


const factors: ProjectFactor[] = [
  { name: "Project Size", weight: 0.3, scoreForTypeScript: 9, scoreForJavaScript: 6 },
  { name: "Team Experience", weight: 0.2, scoreForTypeScript: 7, scoreForJavaScript: 9 },
  { name: "Long-term Maintenance", weight: 0.2, scoreForTypeScript: 9, scoreForJavaScript: 5 },
  { name: "Integration with APIs", weight: 0.15, scoreForTypeScript: 8, scoreForJavaScript: 6 },
  { name: "Development Speed", weight: 0.15, scoreForTypeScript: 7, scoreForJavaScript: 8 },
];


function calculateScore(factors: ProjectFactor[], forTypeScript: boolean): number {
  return factors.reduce((total, factor) => {
    const score = forTypeScript ? factor.scoreForTypeScript : factor.scoreForJavaScript;
    return total + (score * factor.weight);
  }, 0);
}


const typeScriptScore = calculateScore(factors, true);
const javaScriptScore = calculateScore(factors, false);


console.log(`TypeScript Score: ${typeScriptScore.toFixed(2)}`);
console.log(`JavaScript Score: ${javaScriptScore.toFixed(2)}`);
console.log(`Recommendation: ${typeScriptScore > javaScriptScore ? 'Use TypeScript' : 'Use JavaScript'}`);
Enter fullscreen mode Exit fullscreen mode

In conclusion, both TypeScript and JavaScript have their places in React development, making the React TypeScript vs JavaScript decision a critical one. TypeScript offers stronger typing and better tooling support, which can lead to more maintainable and error-free code, particularly in larger projects. On the other hand, JavaScript's simplicity and lower barrier to entry make it an ideal choice for smaller projects or when working with developers who are new to static typing.

Ultimately, the choice between React TypeScript vs JavaScript in React development depends on your project's specific needs, team expertise, and long-term goals. By understanding the strengths and weaknesses of each approach, you can make an informed decision that will set your project up for success.

Top comments (0)