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.
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
Create a functional component with TypeScript:
// src/components/Greeting.tsx
import React from 'react';
interface GreetingProps {
name: string;
}
const Greeting: React.FC = ({ name }) => {
return Hello, {name}!
;
};
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.React.FC
type provides type checking and autocomplete for propsApp.tsx
:
// src/App.tsx
import React from 'react';
import Greeting from './components/Greeting';
const App: React.FC = () => {
return (
);
};
export default App;
App
component imports and uses the Greeting
component, passing “TypeScript” as the name
prop.
Hello, 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(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
Count: {count}
);
};
export default Counter;
useState
is used to create a state variable count
initialized to 0.useEffect
updates the document title whenever count
changes.
Count: 0
[Increment button]
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 = ({ userName, age }) => {
const [state, setState] = useState({ email: '' });
return (
{userName} ({age})
setState({ email: e.target.value })}
placeholder="Enter email"
/>
);
};
export default UserProfile;
UserProfileProps
defines the props for the component, including userName
and age
.UserProfileState
defines the state, including email
.useState
manages the email
state.
[Displays userName and age]
[Email input field]
Create a new Angular project using Angular CLI:
npx create-react-app my-react-app --template typescript
cd my-react-app
Create a component with TypeScript:
// src/app/components/greeting/greeting.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `Hello, {{name}}!
`,
})
export class GreetingComponent {
@Input() name: string = '';
}
GreetingComponent
is decorated with @Component
, defining its selector and template.@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
component is used in the main template, passing “TypeScript” as the name
input.
Hello, TypeScript!
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;
}
}
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: `
- {{ user.name }}
`,
})
export class UserListComponent implements OnInit {
users: User[] = [];
constructor(private userService: UserService) {}
ngOnInit(): void {
this.users = this.userService.getUsers();
}
}
UserListComponent
uses UserService
to get the list of users.ngOnInit
lifecycle hook fetches users when the component is initialized.
- John Doe
Create a new Vue project using Vue CLI:
vue create my-vue-app
cd my-vue-app
vue add typescript
Create a component with TypeScript:
Hello, {{ name }}!
defineComponent
function is used to create the component.props
define the input properties, with name
being a required string.App.vue
:
App.vue
imports and uses the Greeting
component, passing “TypeScript” as the name
prop.
Hello, 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: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
increment({ commit }) {
commit('increment');
}
},
getters: {
getCount(state): number {
return state.count;
}
}
});
State
interface defines the structure of the store’s state.createStore
initializes the Vuex store with state, mutations, actions, and getters.
Count: {{ count }}
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.
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 !❤️