William Fallon
William Fallon

Reputation: 35

Is there a concise way of getting object properties from a parameter that is a union of the same type, of object or array?

Given the following:

// External code, can't change
type Point = {
  x: number;
  y: number;
};

export const getPointData: (Point | Point[]) = (id: number) => {
  return getPoints(id);
}
// Our code
import { getPointData } from "something";

const pointData = getPointData(0); // returns as Coordinates | Coordinates[]

Now here I can check the type of coordinates, but Point isn't exported from the library, so it would be kinda hack-ish I think. I could also check if the data is an Array, but the question is if there is a more concise way of doing that.

Here is my current solution. Is this the only way?

const points = Array.isArray(pointData) ? 
  { pointData[0].x, pointData[0].x } : 
  { pointData.x, pointData.x }

Upvotes: 1

Views: 21

Answers (1)

beautifulcoder
beautifulcoder

Reputation: 11330

Yes, the isArray technique is legit and really the best way. With unions the compiler needs type narrowing to be able to figure out the type. A isArray check works for both the TypeScript compiler and the JS runtime, so you get both covered with this one simple call.

Upvotes: 1

Related Questions