I have objects with properties. These properties can either be single valued, or list valued and some properties are optional, means, they could be undefined. So here are some example objects:
type A = {
myProp: string;
otherProp?: number;
}
type B = {
coolProp?: boolean[];
someProp: SomeOtherType[];
}
edit:
Now, I implemented a function, that takes such an object and the name of a property and returns that property as it was, for one exception: If the property is NOT optional AND NOT an array, it returns that property as an array with the original type as an array type.
Now, I implemented a function, that takes such an object and the name of a property and returns that property as it was, for one exception: If the property is NOT an array, it returns that property as an array with the original type as an array type.
So for example, properties from type B from above would not change, but myProp: string; from type A would become: myProp: string[];. otherProp?: number would also stay the same.
So for example, properties from type B from above would not change, but myProp: string; from type A would become: myProp: string[];. otherProp?: number would become otherProp?: number[].
Now I want to put this behaviour into a return type definition in an interface, but I cannot for the life of me figure out, how to make it work.
My best attempt was:
getPropFromObject<O, P extends keyof O>(node: O, propName: P):
any[] extends O[P] ? O[P] : O[P] extends undefined ? O[P] : O[P][]
but it fails for single optional props like otherProp?: number;
How would a correct type definition look like?