简体   繁体   中英

TypeScript type declaration (d.ts) for destructing function payload

Using WebStorm. TypeScript v4.6.2

I have a function inside regular JavaScript file index.js . Next to it I have types declaration file index.d.ts . The sole purpose of this type declaration file is to get autocomplete suggestions.

Inside JS file I have a function:

module.exports.myFunction = async ({foo}) => {
  foo. // <-- expecting to get suggestion "bar"
}

How TypeScript types declaration file need to look to provide autocomplete for bar which is inside of this foo ?

Trying to do like so:

interface payload {
  foo: {
    bar: string;
  };
}

declare function myFunction(object: payload): any;

export default myFunction;

Getting such "suggestions":

在此处输入图像描述

If I require this myFunction from any other location, then I do get the suggestions as expected, but I want to get that suggestion inside of myFunction itself:

在此处输入图像描述

Files structure:

在此处输入图像描述

TypeScript does not work in a magic way, in your case the best way to make it work is to export the interface and import it in a JSDoc comment to be usable in the function typing. So your files should look like this:

// index.d.ts file

export interface Payload { // Interface name should be capitalized
  foo: {
    bar: string;
  };
}
// index.js file

/**
 * @typedef {import('.').Payload} Payload
 */

/**
 * @param {Payload} param
 */
const myFunction = async ({ foo }) => {
  foo. // <-- You will get here the suggestion for "bar"
};

module.exports = { myFunction };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM