Skip to content

TypeScript Usage Guide

Robin Jr edited this page Sep 26, 2025 · 2 revisions

๐Ÿ“˜ TypeScript Usage Guide

This page explains how to use ytsearch.js with TypeScript. Starting from v2.1.0, the package now exports its internal types so you can get full type safety in your projects.


โœ… Type Exports

The following types are available for direct import from the package:

import type {
  SearchOptions,
  PlaylistOptions,
  SearchType,
  SortType,
  Thumbnail,
  Author,
  VideoResult,
  ChannelResult,
  PlaylistResult,
  SearchResultMeta,
  SearchResult,
  PlaylistMetadata,
  PlaylistInfo,
  PlaylistVideo,
  PlaylistDetailsResult,
  VideoDetailsResult,
} from "ytsearch.js";

๐Ÿ”น Example: Search API with Types

import { searchYouTube } from "ytsearch.js";
import type { SearchResult } from "ytsearch.js";

async function run() {
  const result: SearchResult = await searchYouTube("lofi hip hop", {
    type: "any",
    limit: 20,
  });

  console.log(result.videos[0].title);
  console.log(result.metadata.estimatedResults);
}

run();

The return value is strongly typed โ€” for example, hovering over result.videos in your editor will show VideoResult[].


๐Ÿ”น Example: Playlist API with Types

import { getPlaylistItems } from "ytsearch.js";
import type { PlaylistDetailsResult } from "ytsearch.js";

async function run() {
  const playlist: PlaylistDetailsResult = await getPlaylistItems(
    "PLFgquLnL59amEA43C6M7D9Btqv9iO4nV_",
    { limit: 25 }
  );

  console.log(playlist.info.title);
  console.log("Videos loaded:", playlist.videos.length);
}

run();

๐Ÿ”น Example: Video Details with Types

import { getVideoDetails } from "ytsearch.js";
import type { VideoDetailsResult } from "ytsearch.js";

async function run() {
  const video: VideoDetailsResult = await getVideoDetails("dQw4w9WgXcQ");
  
  console.log(video.title);
  console.log(video.author.name);
}

run();

๐Ÿ“ฆ Benefits of Type Exports

  • Type-safe API: Get autocompletion, validation, and documentation inline in your editor.
  • Consistent naming: All result objects now share common base fields (id, title, url, thumbnails, author, etc.).
  • Flat exports: No need for namespace imports โ€” everything is available directly.

โš ๏ธ Notes

  • searchYouTube returns a different structure depending on the type you pass. If you use any, expect the object with multiple arrays (videos, channels, playlists, etc.). If you pass a specific type (e.g., "video"), the other arrays will be empty.
  • Pagination helpers like nextPage() also return typed results.

Clone this wiki locally