如何解决Typescript:如何使用自动补全功能向函数动态添加方法?
作为Typescript的新手,我无法理解如何将方法附加到函数。该代码可以工作,但是类型不能正确导出以自动完成。可以请别人帮忙,告诉我我做错了什么吗?
import * as CSS from 'csstype';
export type AsType = 'div' | 'span' | 'main';
export interface InstanceType {
/**
* Set HTML tag
* @param as Tag or component
*/
as: (tagName: AsType) => any;
}
// base has methods render(props: CSS.Properties) and as(a: AsType)
const BoxInstance = new Base();
function attachMethods(Component,instance) {
Component.as = function as(asProp: AsType) {
return instance.as(asProp);
}
}
function Box(props: CSS.Properties): InstanceType {
return BoxInstance.render(props);
}
attachMethods(Box,BoxInstance);
在另一个模块中,像这样导入Box,但是自动补全功能不起作用。我使用Microbundle,因此应正确创建* .d.ts。 Box呈现一个react组件。
import { Box } from 'package';
// autocompletion or JSDoc does not work here
const Boxi = Box.as('div');
// returns <div>Box</div>
<Boxi>Box</Boxi>
还尝试了Object.assign喜欢here所述的内容,而没有任何更改。
const Box: InstanceType = Object.assign(
(props: CSS.properties) => BoxInstance.render(props),{
as: function as(asProp: AsType) {
return instance.as(asProp);
}
}
)
已编辑28.08
根据Aluan Haddad的回答,JSDoc的参数名称错误。它应该是。但是JSDoc无法正常工作,因为InstanceType不正确。请查看ccarton的答复。
* @param tagTame - Tag or component
已编辑29.08 尝试了一种解决方法。这样可以消除打字稿错误,tsdoc可以正常工作。
interface ComponentType extends InstanceType {
(props: CSS.Properties): any // or ReturnType<typeof render> function
}
const Box: ComponentType = function Box(props: CSS.Properties) {
return Box.render(props);
} as ComponentType;
游乐场
将所有类型设置为我仍然以cannot invoke as function或as is missing in type结尾的任何类型。
解决方法
如果更改attachMethods
以返回修改后的对象,则可以通过一些类型转换来实现所需的功能。我们还应该使用Object.defineProperty
作为修改现有对象的最安全方法:
function attachMethods<T> (component: T,instance: InstanceType): T & InstanceType {
Object.defineProperty(component,'as',{
value: (asProp: AsType) => instance.as(asProp)
})
return component as any
}
function BoxFunction (props: CSS.Properties): InstanceType {
return boxInstance.render(props);
}
const Box = attachMethods(BoxFunction,boxInstance);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。