Fullstack Development

261497: Fullstack Development

261497: Fullstack Development

History

261497: Fullstack Development

Where is JS?

  • Browser
    • Manipulate DOM.
  • Host OS
261497: Fullstack Development

Activity

  • Run console.log in a browser and in an OS.
261497: Fullstack Development

Learning JS

261497: Fullstack Development

261497: Fullstack Development

What is TypeScript?

  • TypeScript is a super set of JavaScript.
261497: Fullstack Development

Why TypeScipt?

  • Improves your productivity while helping avoid bugs.
    • Catch bugs at the compile-time instead of at runtime.
  • Brings the future JavaScript to today.
    • You can use the new JavaScript features before web browsers (or other environments) fully support them.
  • More competitive in job market.
261497: Fullstack Development

How it works?

  1. Write TypeScript codes. (.ts files)
  2. Compile the TypeScript codes into plain JavaScript codes (.js files) using a TypeScript compiler.
  3. Run JavaScript codes in an environment that JavaScript runs.
261497: Fullstack Development

Tools

261497: Fullstack Development

Demo

261497: Fullstack Development
let a = 10;
a.slice(0, 1); // See error message
let a: number;
a = "Hello"; // See error message
let a: number;
// Try typing "a" and trigger intellisense.
261497: Fullstack Development

Defining types

  • Types by inference
    • TypeScript knows the JavaScript language and will generate types for you in many cases.
  • Type by specification
    • We define it ourselves.
    • Keywords type, interface
261497: Fullstack Development

Type by inference

const user = {
  name: "Hayes",
  id: 0,
};

user.name = 20; // Error
console.log(user.food); // Error
  • TypeScript already knows the type of this variable.
261497: Fullstack Development

Type by specification

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

or

type User = {
  name: string;
  id: number;
};
261497: Fullstack Development

Type Annotation

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

// type User = {
//   name: string;
//   id: number;
// };

const user: User = {
  name: "Hayes",
  id: 0,
  age: 30, // Error
};
261497: Fullstack Development

type vs interface

  • They are very similar, and for the most common cases act the same.
  • However, TypeScript doc recommends interface.
    • interface provides better error message.
    • interface can be extended.
261497: Fullstack Development

More type demo

261497: Fullstack Development

Type utilities

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

// Extend
interface UserExtended extends User {
  isActive: boolean;
}

More information

261497: Fullstack Development

Function (argument type)

// Give warning
function sumNumber(a, b) {
  return a + b;
}

// OK
function sumNumber(a: number, b: number) {
  return a + b;
}
261497: Fullstack Development

Function (type guards)

// Hover cursor on "text" to see the type
function greeter(text: string | null | undefined) {
  if (!text) {
    console.log("...");
    return;
  }
  console.log(text);
}
261497: Fullstack Development

Generics

Generics provide variables to types.

interface Backpack<Type> {
  items: Type[];
  add: (obj: Type) => void;
  get: () => Type;
}

const backpack: Backpack<string> = {
  items: ["1", "2"],
  add: (myStr) => {
    myStr.slice(0, 1);
  },
  get: () => {
    return "Hi";
  },
};
261497: Fullstack Development

Use Typescript in NodeJS project

261497: Fullstack Development

Setup

  • npm i -g pnpm (Alternative package manager)
  • npm init es6 (What?)
  • pnpm install -D typescript tsx @types/node
  • Create ./src directory
261497: Fullstack Development
  • Create ./src/index.ts
function sayHello(name: string) {
  console.log("Hello " + name);
}

sayHello("World");
261497: Fullstack Development

Compile

  • npx tsc src/index.ts --outDir dist

Run (node)

  • node ./dist/index.js

Run (tsx)

  • npx tsx ./src/index.ts
261497: Fullstack Development

Use TS configuration file

  • npx tsc --init

  • Modify tsconfig.json

{
  "compilerOptions": {
    "target": "es2022",
    "module": "nodenext",
    "outDir": "./dist"
  },
  "include": ["./src/**/*"]
}
261497: Fullstack Development

Use TS configuration file (cont)

  • Now just type npx tsc
  • Use npx tsc --showConfig to see config.
261497: Fullstack Development

Code - Async

async function getData() {
  const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
  return await res.json();
}

getData().then((data) => console.log(data));
261497: Fullstack Development

Code - Import

./src/lib.ts

export const name = "Tom";

./src/index.ts

import { name } from "./lib.js";

sayHello(name);
261497: Fullstack Development

Code - FS

import * as fs from "fs";
import { fileURLToPath } from "url";
import { dirname } from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const dir = fs.readdirSync(__dirname);
console.log(dir);
  • Fix __dirname is not defined error (Ref).
261497: Fullstack Development

Using TSconfig template

  • pnpm install @types/node @tsconfig/node-lts @tsconfig/node-ts (What)

./tsconfig.json

{
  "extends": [
    "@tsconfig/node-lts/tsconfig.json",
    "@tsconfig/node-ts/tsconfig.json"
  ],
  "compilerOptions": {
    "outDir": "./dist"
  },
  "include": ["./src/**/*"]
}
261497: Fullstack Development

TypeScript - NextJS

261497: Fullstack Development

Installation

npx create-next-app@latest

261497: Fullstack Development

./tsconfig.json

{
  // ...
  "paths": {
    "@app/*": ["./src/app/*"],
    "@components/*": ["./src/components/*"]
  }
}
261497: Fullstack Development

./src/app/globals.css

@import "tailwindcss";

// Remove everything else
261497: Fullstack Development

./src/components/card.tsx

import { FC } from "react";

interface Props {
  title: string;
  text?: string;
}

const Card: FC<Props> = ({ title, text }) => {
  return (
    <div className="border border-gray-300 p-2 rounded shadow-sm flex flex-col items-center">
      <div className="font-bold text-lg text-gray-800">{title}</div>
      <div className="text-gray-600">{text ?? "...."}</div>
    </div>
  );
};

export default Card;
261497: Fullstack Development

./src/app/page.tsx

import Card from "@components/Card";

export default function Home() {
  return (
    <div className="container flex m-2 gap-2">
      <Card title="Card 1" />
      <Card title="Card 2" text="Content Here" />
    </div>
  );
}
261497: Fullstack Development