Home > Software engineering >  Typescript type within object array notation
Typescript type within object array notation

Time:12-22

I cannot understand this code I see in a file. What on earth would this be doing?

const user = rowData as NonNullable<ApiResult["getUsers"]["data"][number]["users"]>[number];

How can you use a type (number) to look at the property of an object? Note that ApiResult is some graphql generated type and that this code is found within a renderCell for a mui data grid GridColumns array.

CodePudding user response:

How can you use a type (number) to look at the property of an object?

An array is an object, and has values at numbered keys, so ArrayType[number] would be a union of the types of each element of the array.


NonNullable<Type> Constructs a type by excluding null and undefined from Type.

Here's an example of what the data structure is expected to extend, using an arbitrary User type. You can visit the TS playground link and mouseover the lettered type names A through F to see what the IntelliSense thinks the types are:

TS Playground

type User = {
  one: 'This is';
  two: 'the targeted type';
};

type ApiResult = {
  getUsers: {
    data: Array<{
      users: Array<User> | null | undefined;
    }>;
  };
};

declare const rowData: unknown;
const user = rowData as NonNullable<ApiResult["getUsers"]["data"][number]["users"]>[number];

// examine hierarchy:
type A = ApiResult
type B = ApiResult["getUsers"]
type C = ApiResult["getUsers"]["data"]
type D = ApiResult["getUsers"]["data"][number]
type E = ApiResult["getUsers"]["data"][number]["users"]
type F = NonNullable<ApiResult["getUsers"]["data"][number]["users"]>[number]

CodePudding user response:

Here is some simple examples for array member lookups:

const fruitsArray = ["apple", "orange"] as const;
type AvilableFruits = typeof fruitsArray[number]; // will be: "apple" | "orange"

const carsArray = [
  { make: "mercdes", class: "C" },
  { make: "mercdes", class: "S" }
] as const;
type AvilableMercedesClasses = typeof carsArray[number]["class"] // will be "C" | "S"
  • Related