Being new to Typescript I cannot understand how to attach a method to a function. The code works but the types are not exported correctly for autocompletion. Can please somebody help and tell me what I am doing wrong?
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);
In another module Box is imported like this, but autocompletion does not work. I use Microbundle so the *.d.ts should be created correctly. Box renders a react component.
import { Box } from 'package';
// autocompletion or JSDoc does not work here
const Boxi = Box.as('div');
// returns <div>Box</div>
<Boxi>Box</Boxi>
Also tried Object.assign liked described here without any change.
const Box: InstanceType = Object.assign(
(props: CSS.properties) => boxInstance.render(props),
{
as: function as(asProp: AsType) {
return instance.as(asProp);
}
}
)
Edited 28.08
According to the answer from Aluan Haddad the parameter name for JSDoc was wrong. It should be. But JSDoc was not working because the InstanceType was not correct. Please see answer from ccarton.
* @param tagTame - Tag or component
Edited 29.08 A workaround tried. This removes typescript errors and TSDoc works.
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;
Playgrounds
Settings all types to any I still end up with either cannot invoke as function or as is missing in type.