Currently, I am creating an extend
function in TypeScript that has the capability to:
- Update the first object with the keys/values of the second when given two objects.
- Append the elements of the second array to the first array when provided with two arrays.
For example:
extend({a: 1}, {b: 2}) → {a: 1, b: 2}
extend([1], [2]) → [1, 2]
This particular function is designed to work only with either two arrays or two objects, not one type mixed with another.
I am currently struggling to define the appropriate type signature for it. Ideally, it should be something along the lines of:
function extend<A, B, StrOrNum extends (string|number)>(
a: {[key: StrOrNum]: A},
b: {[key: StrOrNum]: B}): {[key: StrOrNum]: A&B} {
..
}
However, upon compilation using tsc
, I encounter an error stating that index signatures are limited to only 'string' or 'number':
[ts] An index signature parameter type must be 'string' or 'number'.
(parameter) key: StrOrNum extends string | number
If this were a scenario involving type definition files, I could easily define two function overloads. But can a similar approach be taken during implementation? Or does this issue signify that the function itself lacks coherence—hinting at the need to split it into separate functions like extendObject
and extendArray
?