0

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.

2
  • "getUsers" is also a type; it's a string literal type. The notation T[K] is an indexed access type where T is an object-like type and K a keylike type assignable to keyof T, and then T[K] is the value types you'd get from indexing into an object of type T with a key of type K. If foo is of type Foo, and k is of type "x", and foo[k] is of type string, then Foo["x"] is of type string. Commented Dec 21, 2021 at 21:51
  • Umm. Uhh.. Yes.. Yes of course. Commented Dec 21, 2021 at 23:14

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Okay.. thanks. Seems like pure insanity to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.