How can you access an object's property using a number in TypeScript?
In TypeScript, an array is considered an object with values stored at numbered keys. Therefore, to access the type of each element in the array, you would use ArrayType[number]
.
NonNullable<Type>
creates a type by removing null
and undefined
from the original Type
.
An example is provided below demonstrating the data structure extension with a hypothetical User
type. You can explore IntelliSense suggestions for types A
to F
by visiting the TS Playground link:
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]