Can you explain the significance of `typeof Array[number]` in Typescript?

const people = ['susan', 'captain jack', 'harry'] as const;
type People = typeof people[number];

https://i.sstatic.net/XlnXH.png

The outcome met my expectations, however, I am perplexed by typeof people[number].

Could someone shed light on the meaning of typeof Array[number] in Typescript?

Answer №1

One user, @jcalz, left a detailed comment explaining how a piece of code works, similar to the OP's code:

const fruit = ["apple", "banana", "grape"] as const;
export type Fruit = (typeof fruit)[number]; 'apple'|'banana'|'grape';

The explanation goes on to clarify that typeof fruit results in

Array<"apple" | "banana" | "grape">
, and thus Fruit is essentially equivalent to
(Array<"apple" | "banana" | "grape">)[number]
. Furthermore, it delves into what T[K] signifies in TypeScript, pointing out that it reflects the type of properties in T with keys that match K.

In another insightful comment by @jcalz, technical terms are further elaborated upon:

The concept of T[K] being a lookup type is explained, highlighting its role in retrieving the property type of T corresponding to key K. The usage of (typeof list)[number] is then examined, shedding light on how it retrieves types based on numerically indexed properties within (typeof list), typical of arrays like typeof list with numeric index signatures.

Answer №2

typeof is used to determine the type of the names variable (which is

readonly ['jacob', 'master jung', 'kyuhyun']
). This allows for resolving the types of array or tuple members, known as indexed access types or lookup types.

While syntactically similar to element access, lookup types are written as types.

Here, we are retrieving the type of a specific tuple member (the tuple/array at index), which results in

'jacob' | 'master jung' | 'kyuhyun'
.

Access Playground

Answer №3

I found @OfirD's response to be quite insightful and would suggest giving it a thorough read before delving into my perspective. For me, the concept truly clicked when I witnessed it being applied to both an array and an object in parallel.

I've taken it upon myself to dissect your initial example:

Answer №4

If an element has the Type of Names, it must be included in the array.

For example, you are now able to:

let username: Names = "Alice"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display JSX using the material-ui Button component when it is clicked

When I click on a material-ui button, I'm attempting to render JSX. Despite logging to the console when clicking, none of the JSX is being displayed. interface TileProps { address?: string; } const renderDisplayer = (address: string) => { ...

Mocking a Class Dependency in Jest

I have 4 classes available, and I utilize 3 of them to create an instance of another class. This is how it's done: const repo = new PaymentMessageRepository(); const gorepo = new GoMessageRepository(); const sqsm = new PaymentMessageQueueManager(pr ...

Ways to display all current users on a single page within an application

I have come across a project requirement where I need to display the number of active users on each page. I am considering various approaches but unsure of the best practice in these scenarios. Here are a few options I am considering: 1. Using SignalR 2. ...

Guide on inputting Vue component in props

<template> <v-dialog width="auto" v-model="isShown" transition="dialog-bottom-transition" > <v-card> <v-card-title v-if="title"> {{ title }}</v-card-title> ...

When utilizing the navigation.navigate function, react-navigation v6.0 may present an error message

The Challenge I'm Dealing With One issue I encountered is when I use navigation.navigate('XXXPage'), react-navigation version 6.0 displays the following error message. Argument of type 'string' is not assignable to parameter of ty ...

Managing singleton instances in TypeScript and NextJs across multiple files

Lately, I've been immersed in a personal project that involves creating API endpoints using NextJs and TypeScript to interact with the Discord API via discord.js. Don't worry if you're unfamiliar with the discord API, as the focus here is no ...

Guide on crafting a query with typeorm query builder to extract specific data from the database

I'm a beginner with typeorm in nodejs/nestjs and I'm struggling to create a query to filter course data by instructor's firstname and lastname, course name, and subject. I've tried using 'where' and 'orWhere' but can ...

Transferring information between components, specifically when one of them is a routerOutlet within an Angular application

I need to transfer data from the category component to the product component within the dashboard component. However, I am facing an issue due to the presence of a router outlet inside the product component. View Dashboard Screen dashboard.component.html ...

Exploring the differences between importing all utilities as a whole using `import * as util from "./util"` and importing a specific function only with `import {someFunction

When comparing the two options of importing from a module, which is better: import * as util from "./Util" or import {someFunction} from "./Util"? ...

Is there a memory leak causing Node.js memory growth in the (system)?

I have come across a peculiar memory leak in our live environment, where the heap continues to grow due to (system) objects. Heap snapshot Here is a memory dump showing a spike in memory usage up to 800MB: https://i.sstatic.net/vvEpA.png It seems that t ...

Firebase is storing object values as 'undefined'

My goal is to retrieve user details from my firebase database while using Ionic and Typescript. Here is how I add a user: addToDatabase(user: User) { let isInstructor = user.isInstructor == null ? false : user.isInstructor; this.afDB.list("/users/").push ...

Comparing Necessary and Deduced Generic Types in TypeScript

Can you explain the difference between these two generic types? type FnWithRequiredParam<T> = (t: T) => void type FnWithParamInferred = <T>(t: T) => void From what I understand, FnWithRequiredParam will always require the generic type t ...

What is the appropriate event type to pass to the onKeyPressed function in a React application utilizing MaterialUI and written with Typescript?

I am currently working on a React application using Typescript and MaterialUI, where I have implemented a TextField component. My goal is to capture the value of the input HTML element when the user presses the enter key. To achieve this, I have created ...

Implementing a dependent <select> within an HTML table is a useful feature to enhance user experience and organization of

I have set up a table with editable columns where values can be selected from a drop-down menu. I achieved this by using HTML select. The options in the 'Category tier 2' column are based on the selection made in the 'Category tier 1' c ...

Setting up Electron to utilize TypeScript's baseUrl can be achieved by following a few simple steps

In TypeScript, there is a compiler option known as baseUrl that allows you to use non-relative paths, like: import Command from "util/Command" as opposed to: import Command from "../../../util/Command" While this works fine during compilation, TypeScri ...

Exploring type definition for function arguments in TypeScript and React

There is a high-order component (HOC) designed to store the value of one state for all input and select elements. The output function accepts arguments ({text: Component, select: Component}). An error is displayed while typing an argument: TS2322: Type &ap ...

Securing Email and Password Data in Cypress Tests

Greetings! I trust everyone is in good spirits. My dilemma lies in the fact that I am hesitant to include email and passwords in version control. I am considering using environment variables in my cypress tests and utilizing secrets for runtime value pro ...

When Implementing <Link>, React Router Results in a Blank Page

After updating a number of our dependencies, we have encountered an issue where anchor tags are now causing redirects instead of functioning as before. Whenever we click on an anchor tag, it correctly redirects to the desired URL (e.g., /screens) but only ...

Can you please explain the significance of classes <T> and <U> in Angular 2?

After diving into the Angular 2 TypeScript documentation, I have come across these two classes frequently. Can someone provide a detailed explanation of what they are? One example code snippet from the QueryList API documentation showcases: class QueryLi ...

The parameters 'event' and 'event' are not compatible with each other

I'm currently working on a page that involves submitting a form: import React from 'react'; import Form from 'react-bootstrap/Form'; import { useSignIn } from '../../hooks/Auth/useSignIn'; import { useHistory } from &apos ...