Obtain the type of a Typescript interface property by only providing the property name

Within my Typescript interface, there are numerous properties. In the absence of any instance of this interface, I aim to identify the type of a specific property.

export interface Data {
  foo: string;
  bar: number;
  .
  .
  .
}

One way to achieve this is by using an index signature with a fixed string on Data.

type propType = Data['foo']; // propType = 'string'

Unfortunately, attempting to use a variable in place of the fixed string does not work.

const propName = 'foo';
type propType = Data[propName]; // Errors

The errors encountered are:

  • Type 'any' cannot be used as an index type.ts(2538)
  • 'propName' refers to a value, but is being used as a type here.ts(2749)

These error messages may seem confusing since propName is clearly a string and not of type any, and it is not being utilized as a type in this context.

Update:

Upon further reflection, it becomes evident that what I was attempting to do is unattainable. After much effort, I have come to terms with the fact that interfaces without instances will never possess property or property-type information at runtime.

While the method utilizing type will function during compilation, it is limited to compile-time only. The correct syntax for this approach has been acknowledged in the accepted answer.

(I still find the error messages mentioned in my query to be peculiar.)

Answer №1

There are a couple of solutions available to you. You can either

export interface Data {
  foo: string;
  bar: number;
}

type propName = 'bar';
type propType = Data[propName]; //number

or

export interface Data {
  foo: string;
  bar: number;
}

const propName = 'bar'; //or let propName: 'bar' = 'bar' (both are type literals)
type propType = Data[typeof propName]; //number (typeof propName is 'bar')

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

How Typescript allows variables to act as references to other variables

Imagine having a component with aliases for user data. This approach allows for shorter and cleaner variable names, making the code easier to read: @Component({ selector: 'my-view', templateUrl: './view.component.html', sty ...

Utilizing TypeScript typing with the Express Request object

Encountering an issue with Typescript typings involving the Express Request object. The project is comprised of 2 sub-projects, the user-service and a common project containing reusable Errors and Middlewares. The common folder is added as a dependency in ...

Errors related to missing RxJS operators are occurring in the browser, but are not showing up in Visual Studio

Recently, I encountered a peculiar problem with my Angular4 project, which is managed under Angular-CLI and utilizes the RxJS library. Upon updating the RxJS library to version 5.5.2, the project started experiencing issues with Observable operators. The s ...

Is there a method to remove oneself from ThunkAction?

Is there a way to retrieve reference for unsubscribing from a ThunkAction like the following: export const fetchSomeData = () => async (dispatch: Dispatch, getState: GetState) => { let unsubscribeUserAuth: UnsubscribeUserAuth | null = null; let u ...

Is it possible to dynamically check values in TypeScript?

[Summary] I am looking to dynamically expand my type in TypeScript based on an initial set of values. I want to avoid managing separate arrays/types and instead extend all strings in my type with '_max'. type ExtendedValueTypes = 'money&apos ...

Can an enum be declared in Typescript without specifying a type explicitly?

Within an interface, I have a group of 10+ (optional) members, most of which have a specific set of potential values. To streamline this, I would like to utilize enums. However, creating separate enum types for each member (which are only used once and hav ...

How to Change the Checked State of a Checkbox in React Material UI

I am faced with a situation where I have multiple checkboxes that are used to toggle table columns on and off. The code snippet demonstrates how it looks: const [fields, setFields] = useState<Set<string>>(new Set(["name"])); const ...

Expanding the base class and incorporating a new interface

(Here is an example written using Typescript, but it applies to other cases as well) class IMyInterface { doC:(any) => any; } class Common { commonProperty:any; doA() { } doB() { } } class ClassA extends Common {} class Clas ...

Acquired this as empty

I encountered a strange error message saying "this is null" and I can't figure out what the issue is. Here is my demo on Stackblitz.com with an example code for your reference. Component ngOnInit() { this.getCurrentLocation(); } getCurrentL ...

Modifying iframe src using click event from a separate component in Angular 10

I am looking to dynamically update the src attribute of an iframe when the menu bar is clicked. The menu bar resides in a separate component and includes a dropdown menu for changing languages. Depending on which language is selected, I want to update the ...

Revise the observable to trigger a NgbModal from a service

I have a situation in my Angular 11 service where I am using a Ngbmodal component to subscribe when it is closed. Below is the code snippet: showMessage(messageData: MessageDataDTO): Observable<MessageResult> { return new Observable((result) =&g ...

Having completed "npm link" and "npm i <repo>", the module cannot be resolved despite the presence of "main" and "types" in the package.json file

Here is the contents of my package.json file: { "name": "ts-logger", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "install": "tsc" ...

Tips for transforming alphanumeric characters into value ranges using Typescript

myArray = ["AB01","AB02","AB03","AB04","AB11","BC12","BC13", "SB33"]; // code snippet to create expected string: "AB01-AB04, AB11, BC12-BC13, SB33" The array contains combinations of one or two letter characters followed by two or three digits. Examples ...

Encountering an error of ExpressionChangedAfterItHasBeenCheckedError while trying to refresh the

I'm encountering an issue that I need help with: https://i.stack.imgur.com/4M54x.png whenever I attempt to update the view using *ngIf to toggle on an icon display. This is what my .ts file looks like: @Component({ selector: 'app-orders&ap ...

Choose an alternative following the start-up phase

I have been searching for solutions on various platforms, including Stack Overflow, but nothing seems to work for me. I am struggling with selecting the first option after initializing the box because currently it is choosing a blank option that is not eve ...

The issue lies in the error code TS2315 which states that the type 'observable' is not a generic

I keep encountering an error message that says 'observable is not generic' while importing files. I am working on implementing CRUD operations in Angular 7, where I have created two components for adding and listing employees. The functions for c ...

It appears that the void type can sometimes replace the return type when employed as an interface within TypeScript

interface Check { name: string; _meth(): void; } class ClassDemo implements Check { name: string = 'something'; _meth() { return 'string'; } } Upon examining the interface, it is evident that the return type for _meth should be void. ...

Continue iterating through the range of dates until the first date comes before the second date

I have a pair of Unix timestamps: let start: number = 1632988953; const end: number = 1638259353; My goal is to iterate over these two dates, recalculating the new start date in each iteration. To achieve this, I am utilizing a while loop as shown below ...

What is preventing the value from changing in auth.guard?

I am encountering an issue with the variable loggined, which I modify using the logTog() method. When I call this method, a request is made to a service where the current result is passed to auth.guard. However, in the console, it displays "undefined". Can ...

Having trouble setting a default value for your Angular dropdown? Looking for alternative solutions that actually work?

Objective: Customize the default value for a dropdown menu to switch between English (/en/) and Spanish (/es/) addresses on the website. Challenge: Despite extensive research, including consulting various sources like Angular 2 Dropdown Options Default Va ...