Retrieving the types of all ids from an object

I have a collection as follows:

var myData = [{ id: 'a', value: 1}, { id: 'b', value: 2 }, { id: 'c', value: 3}]

and I am trying to create a function that only accepts certain ids as parameters

function checkId(id: 'a' | 'b' | 'c') { /* */ }

I attempted the following:

var myData = [{ id: 'a', value: 1}, { id: 'b', value: 2 }, { id: 'c', value: 3}]

type Data = typeof myData;
type IdType = keyof Data[number]['id'];

but it resulted in the id being displayed as:

type IdType = number | typeof Symbol.iterator | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | ... 30 more ... | "padEnd"

Answer №1

To rectify the error, simply remove keyof from

type id = keyof OJ[number]['id'];
. By doing this, id will align with string. If you require a more precise type where id should be
"a" | "b" | "c"
, then add as const after the object.

function abc(id: 'a' | 'b' | 'c') { /* */ }

var myObj= [{ id: 'a', value: 1}, { id: 'b', value: 2 }, { id: 'c', value: 3 }] as const

type OJ = typeof myObj;
type id = OJ[number]['id'];
//    ^?

playground

Answer №2

There is no need for the keyof operator in the type id definition:

const myObj = [{ id: 'a', value: 1}, { id: 'b', value: 2 }, { id: 'c', value: 3}];

type OJ = typeof myObj;
type id = OJ[number]['id'];

But keep in mind that with this approach, the type of id will default to string, as TypeScript treats myObj as open-ended and allows for additional elements to be added later.

To avoid this, you can utilize a const assertion:

const myObj = [{ id: 'a', value: 1}, { id: 'b', value: 2 }, { id: 'c', value: 3}] as const;

type OJ = typeof myObj;
type id = OJ[number]['id'];

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

I encountered a function overload error while creating a component for the API service

As a developer venturing into API design with a backend server that handles client-side calls, I find myself grappling with Typescript, transitioning from a Java background. Encountering the error message "No overload matches this call" has left me seeking ...

Utilizing Vuetify in Typescript: Making Use of Data() Properties

ie data() { return { bar: false rules: { foo: (value) => { if (this.bar) {} } } } } The code is functioning correctly. What steps can be taken to help typescript comprehend this? If this is considered a " ...

webpack-dev-server encountered an issue: The module 'URLSearchParams' (imported as 'URLSearchParams') could not be located within the 'url' module

I keep encountering a compilation error with the webpack-serve command, which displays the following message: 'URLSearchParams' (imported as 'URLSearchParams') was not found in 'url'. My setup involves utilizing an Apollo ser ...

Accessing the Component Property from an Attribute Directive in Angular 2

Currently, I am in the process of creating filter components for a grid (Ag-Grid) and planning to use them in various locations. To make these filters accessible from different places, I am developing a wrapper for them. In particular, I am working on a fi ...

Issue encountered when utilizing Next Js in conjunction with react-xarrows results in an error message stating "ReferenceError: Element is not defined"

I'm in the process of creating an application where I need to illustrate connections between components using arrows. I came across a promising project called react-xarrows. However, when attempting to integrate it into my code, I encountered the foll ...

Angular styling and form error issue

Hey there! I'm new to Angular and facing a major issue along with a minor styling problem. Let's start with the big one: <mat-form-field appearance="fill"> <mat-label>Password</mat-label> <input matInput ...

Is OnPush Change Detection failing to detect state changes?

Curious about the issue with the OnPush change detection strategy not functioning properly in this demonstration. My understanding is that OnPush change detection should activate when a property reference changes. To ensure this, a new array must be set e ...

Ways to disregard attributes passed through HTTP

In my application's interface, I manage certain properties that need to be sent to the database while excluding others. One specific property I handle is called state, which can have a value of open or null (closed). This property triggers Angular2&a ...

Updating tooltip text for checkbox dynamically in Angular 6

Can anyone help me with this code? I am trying to display different text in a tooltip based on whether a checkbox is active or not. For example, I want it to show "active" when the checkbox is active and "disactive" when it's inactive. Any suggestions ...

Bundle multiple internal modules in typescript for easy exporting

Currently, I am exploring the idea of implementing TypeScript in node.js. I have been accustomed to using TypeScript with the ///<reference.../> syntax for internal modules. However, as projects grow larger, managing interlinking references between m ...

Understanding how to infer the type of a function when it is passed as an argument

Looking at the images below, I am facing an issue with my function that accepts options in the form of an object where one of the arguments is a transform function. The problem is that while the type of the response argument is correctly inferred for the e ...

Struggling to successfully pass a function as an argument to the setTimeout method within an array in node.js using TypeScript

Here is an example that successfully demonstrates a function being called using setTimeout: function displayMessage(msg: string){ console.log(msg); } setTimeout(displayMessage, 1000, ["Hi!"]; After one second, it will print out "Hi!" to the console. ...

Name values not appearing in dropdown list

Looking for some assistance with displaying a list of names in a dropdown menu using Angular. The dropdown is present, but the names from my array are not appearing. I think it might be a simple fix that I'm overlooking. I'm new to Angular, so an ...

Is there a way to bypass the "Error: Another application is currently displaying over Chrome" message using Javascript or Typescript?

Can the "Another app is displaying over chrome error" be bypassed using JavaScript or TypeScript? Error Message: https://i.stack.imgur.com/iSEuk.png ...

"Typescript: Unraveling the Depths of Nested

Having trouble looping through nested arrays in a function that returns a statement. selectInputFilter(enteredText, filter) { if (this.searchType === 3) { return (enteredText['actors'][0]['surname'].toLocaleLowerCase().ind ...

Defining the type of a React component class constructor in TypeScript that includes a specific static method

After successfully implementing regular classes, including subclasses, with TypeScript, I encountered an issue when working with React components. The explanation provided by TypeScript was limited. import React from 'react' type Props = { tes ...

Unable to invoke a function in TypeScript from a Kendo template within the Kendo TreeList component

In my TypeScript file for class A, I am encountering an issue with the Kendo TreeList code. I am trying to call a function from the Kendo template. export class A{ drillDownDataSource: any; constructor() { this.GetStatutoryIncomeGrid ...

What is the best approach to re-establish a websocket connection in TypeScript?

Encountering an issue when trying to add a "retry()" method: ERROR in src/app/films.service.ts(28,20): error TS2339: Property 'retry' does not exist on type 'WebSocketSubject'. this.wsSubject.retry().subscribe( (msg) => this. ...

When an email link is clicked in Angular, Internet Explorer is automatically logged out and needs to be refreshed

I'm currently working on a project using an Angular 4 Application. One of the elements in my HTML code is an href link that has a mailto: email address. The issue I'm facing is that when I click on this link while using IE11, either I get autom ...

Angular 2 Final Router Encounters Error

I have implemented a basic router in my application to accommodate a URL structure like www.myhost.com/mission/myguid. I have reviewed the tutorials on the Angular site, but I haven't found any discrepancies. The "normal" routes such as www.myhost.com ...