0

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);

1 Answer 1

1

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']
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the quick answer! A couple of questions : 1. Where should I put index.d.ts ? I tried to put in the same directory as YoutubeVideo.ts, but with no effect. 2. When I put it in node_modules/@types/react-native-ytdl/, function ytdl is fine, but not getBasicInfo. Note that in react-native-ytdl implementation, getBasicInfo is an attribute of ytdl.
@Philippe index.d.ts should typically be placed in the top-level source folder. Then include it by adding it to the list for the includes config in tsconfig.json. I have updated the answer to also indicate that ytdl also has a property called getBasicInfo
After applying your updates, there is no problem any more in VSCode editor, but when I run the program, I have TypeError: (0 , _reactNativeYtdl.getBasicInfo) is not a function
It's not a big issue, as return await ytdl.getBasicInfo(url); works. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.