Search code examples
typescriptdefinitelytyped

Adding type definitions for javascript functions


I have this typescript which works:

import ytdl from 'react-native-ytdl';

type DirectLink = {
  url: string;
  headers: any[];
};

type VideoFormat = {
  itag: number;
  url: string;
  width: number;
  height: number;
};

type BasicInfo = {
  formats: VideoFormat[];
};

export default class YoutubeVideo {
  static root: string = 'https://www.youtube.com/watch?v=';

  async getDirectLink(id: string): Promise<DirectLink[]> {
    const url = `${YoutubeVideo.root}${id}`;
    return await ytdl(url, {quality: 'highestaudio'});
  }

  async getBasicInfo(id: string): Promise<BasicInfo> {
    const url = `${YoutubeVideo.root}${id}`;
    return await ytdl.getBasicInfo(url);
  }
}

Now I want to add type definitions, so I created node_modules/@types/react-native-ytdl/index.d.ts which contains :

export default function ytdl(link: string, options: any): Promise<any>;

this make await ytdl(url, {quality: 'highestaudio'}) not complaining any more.

Now what should I do for getBasicInfo so that I can write ?

import ytdl, {getBasicInfo} from 'react-native-ytdl';
...
return await getBasicInfo(url);

Solution

  • You don't have to create your type definitions inside the node_modules folder.

    Any top-level declaration file will do. ex:

    index.d.ts

    declare module 'react-native-ytdl' {
    
      type VideoFormat = {
        itag: number;
        url: string;
        width: number;
        height: number;
      };
    
      type BasicInfo = {
        formats: VideoFormat[];
      };
    
      interface Ytdl {
         (link: string, options: any): Promise<any>;
         getBasicInfo: (url: string | URL) => Promise<BasicInfo>;
      }
    
      const ytdl: Ytdl;
      export default ytdl;
    
      export const getBasicInfo: Ytdl['getBasicInfo']
    }