Skip to main content

Command Palette

Search for a command to run...

The core use-case of TypeScript

Using types (and interfaces) to define a blueprint of a variable

Updated
2 min read
The core use-case of TypeScript
A
I am a web developer from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in

I am going through this course on NextJS (mainly for the sake of Supabase) - and for my project setup, I choose TypeScript instead of plain JavaScript even though the Udemy course uses JavaScript only.

There is a local end-point we have that spits a bit of JSON data

http://localhost:3100/transactions

[
  {
    "id": "1",
    "amount": 100,
    "type": "Expense",
    "description": "Restaurant",
    "category": "Food",
    "created_at": "2023-03-15T23:00:00"
  },
  {
    "id": "2",
    "amount": 159,
    "type": "Expense",
    "description": "Gas",
    "category": "Car",
    "created_at": "2023-03-15T23:00:00"
  },
  {
    "id": "3",
    "amount": 500,
    "type": "Income",
    "description": "Salary",
    "category": "",
    "created_at": "2023-03-15T23:00:00"
  }
]

When we do something like this :

const response = await fetch('http://localhost:3100/transactions');
const transactions = await response.json();

We don't know (in the code) what kind of data we're getting before-hand unless we inspect the JSON response. But if we have the blueprint ready and really know what are the possible response values back, we can define this hard-coded in as TypeScript types which is the very core of TypeScript.

type TransactionType = 'Income' | 'Expense' | 'Saving' | 'Investment';

interface Transaction
{
    id: number;
    type: TransactionType,
    category?: string,
    description: string,
    amount: number,
}
const response = await fetch('http://localhost:3100/transactions');
const transactions: Transaction[] = await response.json();
if (!Array.isArray(transactions)) return <p>No transactions found.</p>;

return (<section className="space-y-4">
    {transactions.map(transaction => <div key={transaction.id}>
        <TransactionItem
            type={transaction.type}
            category={transaction.category}
            description={transaction.description}
            amount={transaction.amount}
        />
    </div>)}
</section>)

Here we “tell” the TypeScript engine that const transactions would be of type Transaction and also it would be an array (of Transactions).

PS: Here TransactionItem is a custom component that does a whole lot of HTML with DIVs, formatting and styling.