TypeScript with Web Development (React, Angular, Vue)

In this chapter, we will delve into how TypeScript integrates with popular web development frameworks: React, Angular, and Vue. TypeScript enhances these frameworks by adding static typing, which helps catch errors during development, improves code readability, and enhances refactoring capabilities. By the end of this chapter, you will have a solid understanding of how to use TypeScript in React, Angular, and Vue applications.

TypeScript with React

Setting Up a React Project with TypeScript

Create a new React project using Create React App with TypeScript template:

				
					npx create-react-app my-react-app --template typescript
cd my-react-app

				
			

Understanding TypeScript in React Components

Create a functional component with TypeScript:

				
					// src/components/Greeting.tsx
import React from 'react';

interface GreetingProps {
  name: string;
}

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

export default Greeting;

				
			

Explanation:

  • GreetingProps interface defines the props expected by the Greeting component.
  • Greeting is a functional component that takes name as a prop and returns an h1 element.
  • The React.FC type provides type checking and autocomplete for props

Use the component in App.tsx:

				
					// src/App.tsx
import React from 'react';
import Greeting from './components/Greeting';

const App: React.FC = () => {
  return (
    <div className="App">
      <Greeting name="TypeScript" />
    </div>
  );
};

export default App;

				
			

Explanation:

  • The App component imports and uses the Greeting component, passing “TypeScript” as the name prop.
  • When you run the app, you should see “Hello, TypeScript!” displayed in the browser.

Output:

				
					Hello, TypeScript!

				
			

Using Hooks with TypeScript

Example of using useState and useEffect with TypeScript:

				
					// src/components/Counter.tsx
import React, { useState, useEffect } from 'react';

const Counter: React.FC = () => {
  const [count, setCount] = useState<number>(0);

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default Counter;

				
			

Explanation:

  • useState is used to create a state variable count initialized to 0.
  • useEffect updates the document title whenever count changes.
  • The component renders the count and a button to increment it.

Output:

				
					Count: 0
[Increment button]

				
			

Props and State Types

Define types for props and state:

				
					// src/components/UserProfile.tsx
import React, { useState } from 'react';

interface UserProfileProps {
  userName: string;
  age: number;
}

interface UserProfileState {
  email: string;
}

const UserProfile: React.FC<UserProfileProps> = ({ userName, age }) => {
  const [state, setState] = useState<UserProfileState>({ email: '' });

  return (
    <div>
      <h1>{userName} ({age})</h1>
      <input
        type="email"
        value={state.email}
        onChange={(e) => setState({ email: e.target.value })}
        placeholder="Enter email"
      />
    </div>
  );
};

export default UserProfile;

				
			

Explanation:

  • UserProfileProps defines the props for the component, including userName and age.
  • UserProfileState defines the state, including email.
  • useState manages the email state.
  • The component renders the user’s name, age, and an input field for the email.

Output:

				
					[Displays userName and age]
[Email input field]

				
			

TypeScript with Angular

Setting Up an Angular Project with TypeScript

Create a new Angular project using Angular CLI:

				
					npx create-react-app my-react-app --template typescript
cd my-react-app

				
			

Understanding TypeScript in Angular Components

Create a component with TypeScript:

				
					// src/app/components/greeting/greeting.component.ts
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-greeting',
  template: `<h1>Hello, {{name}}!</h1>`,
})
export class GreetingComponent {
  @Input() name: string = '';
}

				
			

Explanation:

  • GreetingComponent is decorated with @Component, defining its selector and template.
  • The @Input decorator indicates that name is an input property that can be passed from the parent component.

Use the component in app.component.html:

				
					
<app-greeting name="TypeScript"></app-greeting>

				
			

Explanation:

  • The app-greeting component is used in the main template, passing “TypeScript” as the name input.
				
					Hello, TypeScript!

				
			

Services and Dependency Injection

Create a service with TypeScript:

				
					// src/app/services/user.service.ts
import { Injectable } from '@angular/core';

export interface User {
  id: number;
  name: string;
}

@Injectable({
  providedIn: 'root',
})
export class UserService {
  private users: User[] = [{ id: 1, name: 'John Doe' }];

  getUsers(): User[] {
    return this.users;
  }
}

				
			

Explanation:

  • UserService is decorated with @Injectable, making it available for dependency injection.
  • User interface defines the structure of a user.
  • getUsers method returns the list of users.

Use the service in a component:

				
					// src/app/components/user-list/user-list.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService, User } from '../../services/user.service';

@Component({
  selector: 'app-user-list',
  template: `
    <ul>
      <li *ngFor="let user of users">{{ user.name }}</li>
    </ul>
  `,
})
export class UserListComponent implements OnInit {
  users: User[] = [];

  constructor(private userService: UserService) {}

  ngOnInit(): void {
    this.users = this.userService.getUsers();
  }
}

				
			

Explanation:

  • UserListComponent uses UserService to get the list of users.
  • ngOnInit lifecycle hook fetches users when the component is initialized.
  • The component template displays the list of user names.

Output:

				
					- John Doe

				
			

TypeScript with Vue

Setting Up a Vue Project with TypeScript

Create a new Vue project using Vue CLI:

				
					vue create my-vue-app
cd my-vue-app
vue add typescript

				
			

Understanding TypeScript in Vue Components

Create a component with TypeScript:

				
					
<template>
  <h1>Hello, {{ name }}!</h1>
</template> <script lang="ts" type="litespeed/javascript">import{defineComponent,PropType}from 'vue';export default defineComponent({props:{name:{type:String as PropType<string>,required:!0}}})</script> 
				
			

Explanation:

  • defineComponent function is used to create the component.
  • props define the input properties, with name being a required string.

Use the component in App.vue:

				
					
<template>
  <div id="app">
    <Greeting name="TypeScript" />
  </div>
</template> <script lang="ts" type="litespeed/javascript">import{defineComponent}from 'vue';import Greeting from './components/Greeting.vue';export default defineComponent({components:{Greeting}})</script> 
				
			

Explanation:

  • App.vue imports and uses the Greeting component, passing “TypeScript” as the name prop.

Output:

				
					Hello, TypeScript!

				
			

Using Vuex with TypeScript

Set up a Vuex store with TypeScript:

				
					// src/store/index.ts
import { createStore } from 'vuex';

export interface State {
  count: number;
}

export default createStore<State>({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    increment({ commit }) {
      commit('increment');
    }
  },
  getters: {
    getCount(state): number {
      return state.count;
    }
  }
});

				
			

Explanation:

  • State interface defines the structure of the store’s state.
  • createStore initializes the Vuex store with state, mutations, actions, and getters.

Use the store in a component:

				
					
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template> <script lang="ts" type="litespeed/javascript">import{defineComponent,computed}from 'vue';import{useStore}from 'vuex';import{State}from '../store';export default defineComponent({setup(){const store=useStore<State>();const count=computed(()=>store.getters.getCount);const increment=()=>{store.dispatch('increment')};return{count,increment}}})</script> 
				
			

Explanation:

  • useStore hook is used to access the Vuex store.
  • computed creates a reactive reference to the count getter.
  • increment dispatches the increment action to update the state.

Output:

				
					Count: 0
[Increment button]

				
			

Using TypeScript with React, Angular, and Vue significantly enhances the development experience by providing static typing, better tooling, and improved code maintainability. Each framework has its own way of integrating TypeScript, but the principles remain the same. By following the examples and explanations provided in this chapter, you should have a strong foundation for developing TypeScript applications with these popular frameworks. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India