I have a function which can have multiple parameters of type Node
or Relationship
or undefined
. It has the following signature:
export function useFormat(...elements: Array<Node | Relationship | undefined>) {
const formattedElements: Array<FormattedNode | FormattedRelationship | undefined> = [];
// do formatting...
return formattedElements;
}
I call it as a React Hook and do some formatting based on the given element type. Then I return a new array with basically the same elements in a different format: Array<FormattedNode | FormattedRelationship | undefined>
.
I would like to know if it is possible for TypeScript to infer the type of each element in the returned array based on the same element in the original array elements
.
For example: the first element in the original array elements[0]
is a Node
, so first element of the returned array formattedElements[0]
will be a FormattedNode
.
I believe you should use overloads here:
Much readable format:
UPDATE
Please keep in mind, these types are not 100% safe because I used
any
in order to make it compatible with overload.Second, it is also better to define more than 1 overload. Since array types is mutable, some times it is hard to write type safe functions without using type assertions or
any
.Now, you know all drawbacks.
Playground
If you want to know more about literal array mappings or tuples, you can refer to my blog
UPDATE - without rest
Playground
This is the case when you need
[...U]
instead ofU
. It helps to infer every element in the array. Try to replace[...U]
withU
inside overload