I am currently working on a unique function that utilizes a Proxy with a get
trap to extract functions from multiple objects. The challenge I am facing is getting TypeScript to recognize these functions at compile time so that I can add them to my interface. How can I make TypeScript acknowledge these functions and allow me to integrate them into my interface?
interface IObject {
(): IFunction;
addAMethod(name: string, fn: (...args: any[]) => any): void;
}
interface IFunction {
list: string[];
option: boolean;
}
const mainFunc: IObject = Object.assign(
(): IFunction => {
const context = {
list: [],
option: true,
};
return new Proxy(context, handler);
},
{
addAMethod(name: string, fn: (...args: any[]) => any) {
Object.assign(core, fn);
},
},
);
const handler = {
get(context: {[key: string]: any}, prop: string, receiver: IFunction) {
if (prop in context) {
return context[prop];
}
if (prop in core) {
return core[prop];
}
},
};
const core = {
evaluate: (val: any) => true,
doSomething: (val: any) => false
}
export default mainFunc;
An example of how this would be used:
import mainFunc from "./mainFunc"
mainFunc().evaluate('wow'); // This should return true
However, the current implementation does not return true because evaluate()
is not included in the type IFunction
. When attempting to add it, an error occurs as TypeScript does not recognize evaluate()
.
// ...
interface IFunction {
list: string[];
option: boolean;
evaluate(val: any): boolean;
}
const mainFunc: IObject = Object.assign(
(): IFunction => {
const context = {
list: [],
option: true,
};
return new Proxy(context, handler); // Error occurs here
},
// ...
);
// ...
const core = {
evaluate: (val: any) => true,
doSomething: (val: any) => false
}
Type '{ list: never[]; option: boolean; }' is not assignable to type 'IFunction'. Property 'evaluate' is missing in type '{ list: never[]; option: boolean; }'.
Do you have any suggestions on how I could properly define the type for evaluate()
?