I am trying to get the Typescript correct for a constructor and factory function, but am still stuck with the below errors when I run it through tsc.
src/tests/lib/mockNconf.ts(16,14): error TS2322: Type '(conf: Conf) => MockNconf' is not assignable to type 'MockNconfConstructor'.
Type '(conf: Conf) => MockNconf' provides no match for the signature 'new (conf: Conf): MockNconf'.
src/tests/lib/mockNconf.ts(18,12): error TS2350: Only a void function can be called with the 'new' keyword.
I have looked at How to define a Typescript constructor and factory function with the same name?, but that relates only to the typescript definition (with a pure javascript implementation).
The code I have is
import * as deepclone from 'lodash.clonedeep';
type Conf = { [key: string]: any };
interface MockNconf {
set(key: string, data: any): void,
get(key: string): any,
clone(): MockNconf
}
interface MockNconfConstructor {
new (conf: Conf): MockNconf;
(conf: Conf): MockNconf;
}
export const MockNconf: MockNconfConstructor = function MockNconf(conf: Conf): MockNconf {
if (!(this instanceof MockNconf)) {
return new MockNconf(conf);
}
this.conf = conf;
};
Object.assign(MockNconf.prototype, {
set: function set(key: string, data: any): void {
if (typeof data === 'undefined') {
if (typeof this.conf[key] !== 'undefined') {
delete this.conf[key];
}
} else {
this.conf[key] = data;
}
},
get: function get(key: string): any {
return this.conf[key];
},
clone: function clone(): MockNconf {
const newConf = deepclone(this.conf);
return new MockNconf(newConf);
}
});
export default MockNconf;