I attempt to write a function fn()
with the following properties:
- Takes a single argument
x
which is an object with optional keys “a” and “b” (for simplicity, each field may be numeric) - It outputs a new object with the same keys as provided in the input object but each field is a specific class (a->A, b->B), i.e. the desired behavior is:
- if I call fn({a: 1, b: 1}) I receive {a: A, b: B}
- if I call fn({b:1}) I receive {b: B} and
- if I call fn({}) I receive {}.
You can take the numeric values in the input object as initialization values for the classes in the output object. Also, new fields “c”, “d”, “e”, … may be added later to this function.
I struggle to set this up on the type level but also in the JS code. I have written the following code which raises Typescript errors:
- Type ‘string’ is not assignable to type ‘keyof OutputObject’.ts(2344)
- Type ‘Partial’ is not assignable to type ‘Pick<OutputObject, K>’.ts(2322)
class A {}
class B {}
interface InputObject {
a: number,
b: number
}
interface OutputObject {
a: A,
b: B
}
// My failed attempt at writing fn()
const fn = <
TObj extends Partial<InputObject>,
K extends keyof TObj
>(x: TObj): Pick<OutputObject, K> => {
let returnValue: Partial<OutputObject> = {}
if (x.a) {
returnValue.a = new A()
}
if (x.b) {
returnValue.b = new B()
}
return returnValue
}