TypeScript with JavaScript Frameworks

TypeScript has become the go-to choice for modern web development, especially when working with popular frameworks like React, Vue, and Angular. By adding static typing to JavaScript, TypeScript helps catch errors early, improves code maintainability, and enhances developer experience through better tooling support. Whether you're starting a new project or migrating an existing one, understanding how TypeScript works with these frameworks will significantly boost your productivity.

Using TypeScript with React

React and TypeScript form a powerful combination that brings type safety to component-based architecture. Here's how you can leverage TypeScript in React projects:

Typing Props and State

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
          interface UserProps {
  name: string;
  age: number;
  isActive?: boolean; // Optional prop
}

const UserCard: React.FC<UserProps> = ({ name, age, isActive = true }) => {
  const [score, setScore] = useState<number>(0); // Typed state

  return (
    <div className={isActive ? 'active' : 'inactive'}>
      <h2>{name}</h2>
      <p>Age: {age}</p>
      <p>Score: {score}</p>
    </div>
  );
};
        

Typing Events

typescript
1
2
3
4
5
6
7
8
9
          const SearchBox = () => {
  const [query, setQuery] = useState<string>('');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setQuery(e.target.value);
  };

  return <input type="text" value={query} onChange={handleChange} />;
};
        

Creating Custom Hooks with Types

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
          function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T) => void] {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch {
      return initialValue;
    }
  });

  const setValue = (value: T) => {
    setStoredValue(value);
    localStorage.setItem(key, JSON.stringify(value));
  };

  return [storedValue, setValue];
}
        

Integrating TypeScript into Vue and Angular Projects

Vue with TypeScript

Vue 3 was designed with TypeScript in mind, offering excellent type support out of the box:

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
          <script setup lang="ts">
import { ref } from 'vue';

interface Product {
  id: number;
  name: string;
  price: number;
}

const products = ref<Product[]>([
  { id: 1, name: 'Laptop', price: 999 },
  { id: 2, name: 'Phone', price: 699 }
]);

const total = computed<number>(() => {
  return products.value.reduce((sum, product) => sum + product.price, 0);
});
</script>
        

Angular with TypeScript

Angular is built with TypeScript, making types a first-class citizen:

typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
          import { Component, Input } from '@angular/core';

interface Task {
  id: number;
  title: string;
  completed: boolean;
}

@Component({
  selector: 'app-task-item',
  template: `
    <div [class.completed]="task.completed">
      <input type="checkbox" [checked]="task.completed" (change)="toggleComplete()">
      {{ task.title }}
    </div>
  `
})
export class TaskItemComponent {
  @Input() task!: Task;

  toggleComplete() {
    this.task.completed = !this.task.completed;
  }
}
        

Benefits of TypeScript in Frontend Development

1. Early Error Detection

TypeScript catches type-related errors during development rather than at runtime:

typescript
1
2
3
4
5
          // TypeScript will flag this error immediately
const calculateTotal = (items: { price: number }[]) => {
  return items.reduce((total, item) => total + item.price, '0');
  // Error: Argument of type 'string' is not assignable to parameter of type 'number'
};
        

2. Improved Code Maintainability

TypeScript makes large codebases more manageable by:

  • Providing clear interfaces between components
  • Enabling safe refactoring with confidence
  • Serving as documentation through type definitions

3. Enhanced Developer Experience

Modern IDEs leverage TypeScript to offer:

  • Intelligent code completion
  • Accurate code navigation
  • Real-time error highlighting
  • Better documentation tooltips

4. Framework-Specific Advantages

React Benefits:

  • Proper typing for hooks, props, and context
  • Type checking for Redux actions and reducers
  • Validation for component interfaces

Vue Benefits:

  • Type-safe template expressions
  • Proper typing for Composition API
  • Validation for Vuex store

Angular Benefits:

  • Strong typing for dependency injection
  • Type checking for templates
  • Interface support for services

5. Easier Team Collaboration

TypeScript acts as a communication tool that:

  • Makes code intentions clearer
  • Reduces ambiguity in interfaces
  • Minimizes "guesswork" when working with unfamiliar code

Migration Tips

For existing JavaScript projects:

  1. 1
    Start by renaming files to .tsx (React) or .ts.
  2. 2
    Configure tsconfig.json with strict: false initially.
  3. 3
    Gradually add types to critical parts of your application.
  4. 4
    Enable stricter rules over time as you add more types.

By adopting TypeScript in your framework of choice, you'll build more robust applications while enjoying a smoother development workflow. The initial learning curve pays off quickly through reduced bugs and better maintainability.