作为打字本的新手,我不知道如何将一个方法附加到函数中。代码可以工作,但类型不能正确导出以便自动完成。有人能帮忙告诉我我做错了什么吗?
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。框呈现反应组件。
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喜欢描述这里,没有任何改变。
const Box: InstanceType = Object.assign(
(props: CSS.properties) => boxInstance.render(props),
{
as: function as(asProp: AsType) {
return instance.as(asProp);
}
}
)编辑28.08
根据Aluan的回答,JSDoc的参数名是错误的。应该是这样的。但是JSDoc没有工作,因为InstanceType是不正确的。请看卡尔顿的回答。
* @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;游乐场
发布于 2020-08-26 13:22:59
如果将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);https://stackoverflow.com/questions/63597159
复制相似问题