2024-11-25
TypeScript is a strongly typed superset of JavaScript that adds optional static typing to the language, making it easier to write scalable and maintainable code.
Specify the type of variables, function parameters, and return values to ensure type safety.
let message: string = "Hello, TypeScript";
function add(a: number, b: number): number {
return a + b;
}
Define the shape of objects, ensuring consistency and reusability.
interface User {
name: string;
age: number;
}
const user: User = { name: "Hafis", age: 30 };
Provide a way to define reusable and type-safe components or functions.
function identity<T>(value: T): T {
return value;
}
const num = identity<number>(42);
Define a set of named constants for better code readability.
enum Status {
Active,
Inactive,
Pending,
}
const userStatus: Status = Status.Active;
Create flexible types by combining multiple types.
type ID = string | number; // Union
type UserWithRole = User & { role: string }; // Intersection
Explicitly specify the type when TypeScript cannot infer it.
const someValue: any = "Hello, World";
const stringLength: number = (someValue as string).length;
Organize code into reusable modules and avoid naming conflicts.
export const greet = (name: string): string => `Hello, ${name}`;
Automatically deduce types when possible, reducing the need for annotations.
let count = 42; // inferred as number
Next.js is a React framework with built-in support for TypeScript. Here's how you can implement TypeScript in a Next.js project:
Install necessary dependencies:
npm install --save-dev typescript @types/react @types/node
Create a tsconfig.json file:
npx tsc --init
When you start your Next.js app, it automatically detects TypeScript.
Use .tsx for React components.
// pages/index.tsx
import { FC } from 'react';
const Home: FC = () => {
return <h1>Welcome to TypeScript with Next.js</h1>;
};
export default Home;
Add types to the API handler.
// pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ message: "Hello, API with TypeScript!" });
}
Define props using interface or type.
// components/Greeting.tsx
interface GreetingProps {
name: string;
}
const Greeting: React.FC<GreetingProps> = ({ name }) => {
return <p>Hello, {name}!</p>;
};
export default Greeting;
// Usage in a page
import Greeting from '../components/Greeting';
const Page = () => <Greeting name="Hafis" />;
export default Page;
Define types for fetched data.
// types/User.ts
export interface User {
id: number;
name: string;
email: string;
}
// pages/users.tsx
import { GetServerSideProps } from 'next';
import { User } from '../types/User';
interface UsersPageProps {
users: User[];
}
const UsersPage: React.FC<UsersPageProps> = ({ users }) => (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
export const getServerSideProps: GetServerSideProps = async () => {
const response = await fetch('https://api.example.com/users');
const users: User[] = await response.json();
return { props: { users } };
};
export default UsersPage;
Define reusable global types in types/ or @types/ folders.
Use TypeScript to define custom app or document structure.
// pages/_app.tsx
import type { AppProps } from 'next/app';
function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
export default MyApp;
With TypeScript, you ensure type safety and build scalable applications in Next.js!