Skip to content
Go back

A demo of a blog entry using Keystatic

Hello guys, welcome to the demo!

The Typescript logo, white text with a blue background.
TypeScript, Woah!

Table of contents

Open table of contents

    The table of contents component can be added anywhere to the document, but it should be kept at the top, preferably just under a figure tag, if one is used, and before any other h2 tags.

    Typescript demo

    Use '##' (h2) tags for top level headings, important since the blog title already uses a h1 (improves SEO).

    Defining types

    Keystatic also allows us to easily write inline code examples, or using code blocks. When using code blocks, the language you want to specify must be written in lowercase in order for the styling to apply. e.g. 'ts', not 'TS' or 'TypeScript', etc. 'Python' would be 'py' or 'python'.

    // types.ts
    
    type Role = "admin" | "editor" | "viewer";
    
    interface User {
      id: string;
      name: string;
      email: string;
      role: Role;
      createdAt: Date;
    }
    
    interface CreateUserPayload {
      name: string;
      email: string;
      role?: Role; // optional, defaults to "viewer"
    }
    
    interface UserServiceResponse<T> {
      data: T | null;
      success: boolean;
      error?: string;
    }

    Writing a basic Typescript function

    // userService.ts
    
    import { User, CreateUserPayload, UserServiceResponse } from "./types";
    
    function createUser(
      payload: CreateUserPayload
    ): UserServiceResponse<User> {
      const { name, email, role = "viewer" } = payload;
    
      // Basic validation
      if (!name || !email) {
        return {
          data: null,
          success: false,
          error: "Name and email are required.",
        };
      }
    
      if (!email.includes("@")) {
        return {
          data: null,
          success: false,
          error: "Invalid email address.",
        };
      }
    
      // Simulate creating a user
      const newUser: User = {
        id: crypto.randomUUID(),
        name,
        email,
        role,
        createdAt: new Date(),
      };
    
      return {
        data: newUser,
        success: true,
      };
    }
    

    Using the function

    // main.ts
    
    const result = createUser({ name: "Alice", email: "alice@example.com" });
    
    if (result.success && result.data) {
      console.log(`User created: ${result.data.name} (${result.data.role})`);
      // → User created: Alice (viewer)
    } else {
      console.error(`Error: ${result.error}`);
    }
    
    // With an explicit role
    const adminResult = createUser({
      name: "Bob",
      email: "bob@example.com",
      role: "admin",
    });
    
    console.log(adminResult.data?.role);
    // → admin
    

    You can even add tables from KeystaticNo-way!
    Yes-way!O-kay...

    Some gibberish!

    Wow, Typescript is awesome. 🍅

    • "Propaaah" - Deepash

    Share this post on: