[英]TypeScript type declaration (d.ts) for destructing function payload
Using WebStorm.使用网络风暴。 TypeScript v4.6.2
TypeScript v4.6.2
I have a function inside regular JavaScript file index.js
.我在常规 JavaScript 文件
index.js
中有一个 function 。 Next to it I have types declaration file index.d.ts
.在它旁边我有类型声明文件
index.d.ts
。 The sole purpose of this type declaration file is to get autocomplete suggestions.此类型声明文件的唯一目的是获得自动完成建议。
Inside JS file I have a function:在 JS 文件中我有一个 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
? TypeScript 类型声明文件需要如何查找以为此
foo
内部的bar
提供自动完成功能?
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:如果我从任何其他位置需要这个
myFunction
,那么我确实会按预期获得建议,但我想在myFunction
本身内部获得该建议:
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. TypeScript 不会以神奇的方式工作,在您的情况下,使其工作的最佳方法是导出界面并将其导入 JSDoc 注释中,以便在 function 键入中使用。 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 };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.