Hafis Alrafi

TypeScript Fundamental

2024-11-25

Typescript Main Concept

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.

1. Type Annotations

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;
}

2. Interfaces and Types

Define the shape of objects, ensuring consistency and reusability.

interface User {
  name: string;
  age: number;
}
const user: User = { name: "Hafis", age: 30 };

3. Generics

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);

4. Enums

Define a set of named constants for better code readability.

enum Status {
  Active,
  Inactive,
  Pending,
}
const userStatus: Status = Status.Active;

5. Union and Intersection Types

Create flexible types by combining multiple types.

type ID = string | number; // Union
type UserWithRole = User & { role: string }; // Intersection

6. Type Assertions

Explicitly specify the type when TypeScript cannot infer it.

const someValue: any = "Hello, World";
const stringLength: number = (someValue as string).length;

7. Modules and Namespaces

Organize code into reusable modules and avoid naming conflicts.

export const greet = (name: string): string => `Hello, ${name}`;

8. Type Inference

Automatically deduce types when possible, reducing the need for annotations.

let count = 42; // inferred as number

Implementation in Next.js

Next.js is a React framework with built-in support for TypeScript. Here's how you can implement TypeScript in a Next.js project:

1. Setup TypeScript in Next.js

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.

2. Create a Page with 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;

3. API Routes with TypeScript

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!" });
}

4. TypeScript with Props

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;

5. Fetch Data with TypeScript

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;

6. Global Types

Define reusable global types in types/ or @types/ folders.

7. Custom App and Document

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!