dockerman_20
dockerman_20

Reputation: 55

Typescript type within object array notation

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.

Upvotes: 0

Views: 417

Answers (1)

jsejcksn
jsejcksn

Reputation: 33691

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]

Upvotes: 1

Related Questions