This is largely a continuation of a previous inquiry on a related theme, albeit with some simplification.
The main goal here is to pass an object's attributes and values through a conversion function (which will eventually be a factory builder) and then assign those modified properties to the returned object while also preserving the data types.
Below is the snippet of code I've been working on:
type Config<T extends {[key:string]: number | string}> = {
inst?: T
}
function convert ( value: string ): number;
function convert ( value: number ): string
function convert( value: any ): any {
if ( typeof value === 'number' ) {
return value.toString();
}
return parseInt( value.toString(), 10 );
}
function init<T extends {[key:string]: any}>(db, config: Config<T>): T & {} {
let ret: any = {};
if ( config.inst ) {
for (let [key, value] of Object.entries(config.inst)) {
let res = convert( value );
ret[ key ] = res;
}
}
return ret;
}
let a = convert( '1' ); // `a` now holds a `number`
let b = convert( 2 ); // `b` now contains a `string`
let { strToNum, numToStr } = init( null, { inst: { strToNum: '1', numToStr: 2 } } );
// `strToNum` is a string - but expected to be a number
// `numToStr` is a number - when it should be a string
The convert function seems to be functioning correctly with its overload type, however, implementing the desired typing for the returned object's parameters has proven challenging. Any thoughts or suggestions?