Enhancing JavaScript functions with type definitions

I have successfully implemented this TypeScript code:

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 enhance the type definitions, so I created a file at node_modules/@types/react-native-ytdl/index.d.ts with the content :

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

This change eliminates the error for

await ytdl(url, {quality: 'highestaudio'})
.

Next, I need to make adjustments for getBasicInfo so that I can write ?

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

Answer №1

Creating type definitions outside of the node_modules directory is possible.

Any declaration file at the root level will work, for example:

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']
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up Typescript: The Guide to Declaring a Dependent Property

In my current project, I am working on creating a declaration file for the quadstore library. This library has a class that requires a constructor parameter called contextKey. The value of this parameter determines the name of a field on method arguments. ...

React Typescript is causing issues with the paths not functioning properly

Looking to simplify my import paths and remove the need for deeply nested paths. Currently working with React and TypeScript, I made adjustments to my tsConfig file like so: { "compilerOptions": { "baseUrl": "src", & ...

Angular 11 is causing confusion by incorrectly applying the Http interceptor to sibling modules

Here is the structure of my modules: The HTTP interceptor I provided in core.module.ts is affecting the HTTP client in the translation.module.ts. This is how my core module is set up: @NgModule({ declarations: [DefaultLayoutComponent], providers: [ ...

A Defer statement in TypeScript that mimics Go's functionality

Is there an equivalent to Go's Defer statement in TypeScript? I find it tedious to write cleanup code in various parts of a function. Searching for a simpler alternative. I tried searching on Google, but couldn't locate any relevant information ...

The attribute 'name' cannot be found within the class 'MyComponent'

I'm a beginner in Angular2 and I have no previous knowledge of version 1. Can you help me understand why this error is occurring and guide me on how to fix it? import { Component } from 'angular2/core'; @Component ({ selector: 'my- ...

Encountering a compilation error while trying to utilize a union type in a function parameter within an

As stated on https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html, it is recommended to utilize multiple types for a parameter in a function (refer to the union part) /* OK */ interface Moment { utcOffset(): number; ...

The data structure '{ variableName: string; }' cannot be directly assigned to a variable of type 'string'

When I see this error, it seems to make perfect sense based on what I am reading. However, the reason why I am getting it is still unclear to me. In the following example, myOtherVariable is a string and variableName should be too... Or at least that&apos ...

Expanding a Typescript class with a new method through its prototype

https://i.sstatic.net/3hIOo.png I'm encountering an issue while attempting to add a method to my Typescript class using prototype. Visual Studio is giving me a warning that the function does not exist in the target type. I came across some informati ...

PhpStorm alerts users to potential issues with Object methods within Vue components when TypeScript is being utilized

When building Vue components with TypeScript (using the lang="ts" attribute in the script tag), there is a warning in PhpStorm (version 2021.2.2) that flags any methods from the native JavaScript Object as "Unresolved function or method". For exa ...

Make sure a Typescript array contains a particular value

Currently, I am in the process of developing a dropdown-style component where the value and options are separate props. My goal is to incorporate Typescript to ensure that the value remains a valid option. Although I could perform this validation at runtim ...

A guide on incorporating Typescript into Material UI v5 themes

A similar question has been asked previously, however... I am looking to enhance my color options by adding variants such as success, warning, and more choices within the background category (palette.background). Specifically interested in a lite option t ...

Issue encountered: Dealing with a deadlock error triggered by a single query following the

I have a question about managing a query that runs across multiple micro-services, which can sometimes lead to deadlocks. const handleExecution = async (id: number): Promise<boolean> => { try { const query = ` UPDATE articles a1 ...

Reactivity in Angular Autocomplete with API Integration

I went through all the tutorials on Angular Autocomplete using API to follow the steps. I implemented valueChanges to monitor the form control, used switchMap to send a new request with each keyword change, and then displayed the data in the autocomplete d ...

What is the best way to pinpoint and eliminate a Subject from an Observable?

Currently, I am utilizing a service to gather user responses from a questionnaire. The sequence of events is outlined below: questionnaire.component.ts : serves as the main container that receives data from question.service.ts question-shell.component.ts ...

The specified class is not found in the type 'ILineOptions' for fabricjs

Attempting to incorporate the solution provided in this answer for typescript, , regarding creating a Line. The code snippet from the answer includes the following options: var line = new fabric.Line(points, { strokeWidth: 2, fill: '#999999', ...

Tips for accessing a RouterState from the @ngxs/router-plugin before and during the initialization of other states

Previously, in an Angular 8.0.0 and 3.5.0 NGXS application, I successfully retrieved the RouterState using SelectSnapshot from the @ngxs/router-plugin within other states before component rendering. However, in my latest application, the RouterState now re ...

Declaration of types for invoking the lodash `mapKeys` function

Is there a way to create a function that can map object keys from camelCase to snakeCase, and be used multiple times with different objects? I have already written a function called mapKeysToSnakeCase which does the job, but I'm curious if there is a ...

Tips for defining data types for spreading properties in TypeScript

I'm grappling with adapting this code to function properly in TypeScript type ScrollProps = { autoHide: boolean autoHideTimeout: number autoHideDuration: number } const renderThumb = ({ style, ...props}) => { const thumbStyle = { borde ...

String validation using regular expressions

Below is the code I am using to validate a string using regular expressions (RegEx): if(!this.validate(this.form.get('Id').value)) { this.showErrorStatus('Enter valid ID'); return; } validate(id) { var patt = new RegExp("^[a-zA- ...

React: Issue accessing URL parameters using useParams() within a nested component

In my demo application, there are two components - QuoteDetail and Comments. Both require URL parameters, but I am only able to access them in the parent component. App.tsx: <Switch> // ... <Route path="/quotes" exact> <Al ...