I am working on creating a function fn()
that has the following specifications:
- It takes a single argument
x
which is an object with optional keys "a" and "b" (each field may be numeric for simplicity) - The function should return a new object with the same keys as the input object, but each field should be a specific class (a->A, b->B). The expected behavior is:
- Calling fn({a: 1, b: 1}) should return {a: A, b: B}
- Calling fn({b:1}) should return {b: B}
- Calling fn({}) should return {}
You can use the numeric values in the input object as initialization values for the classes in the output object. Additionally, new fields "c", "d", "e", and so on may be added to this function later.
I am having trouble implementing this on the type level as well as in JavaScript code. The code I have written so far is causing Typescript errors:
- Type 'string' is not assignable to type 'keyof OutputObject'.ts(2344)
- Type 'Partial' is not assignable to type 'Pick
'.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
}