Variable in Typescript declared with a specific type representing an object

Imagine the following interface/type:

interface Ifc {
  fieldA: string;
  fieldB: number;
}

I'm looking for a type that can be assigned to a non-object type variable in TypeScript, indicating the following:

Hello TypeScript, this type is a single type from all types included in the interface Ifc

This allows me to control types in the following way:

// [[ ]] represents a placeholder
let oneFromIfc0: [[Type I can't figure out]] = 'Hey there' // This is fine, as string is part of the Ifc type
let oneFromIfc1: [[Type I can't figure out]] = false // error, since boolean does not match any field in Ifc

In the case of an object, it could be solved with a mapped optional type:

type partialType = {
  [k in keyof Ifc]?: Ifc[k];
}

This essentially tells TypeScript to do the following:

Hello TypeScript, make each field in Ifc optional. Then copy the type of that field to this new field.

However, this approach has some drawbacks when compared to the one I need:

  • Requires interaction with objects rather than scalar values (using o.fieldA instead of fieldA)
  • Allows mapping multiple fields of Ifc to the new object
  • The field name must match consistently with Ifc field names

Answer №1

To find the combined values across all fields in an interface, you can utilize T[keyof T]

interface Interface {
  prop1: string;
  prop2: number;
}

let valueFromInterface1: Interface[keyof Interface] = 'Hello' // valid
let valueFromInterface2: Interface[keyof Interface] = true // invalid

Code Playground

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

Next.js routes taking precedence over storybook routes

I recently completed a storybook project. Now, I am looking to integrate it with another project built on next.js. The issue is that Storybook and next.js each have their own set of routes. I want to streamline the routing process by utilizing next.js and ...

Angularv9 - mat-error: Issue with rendering interpolated string value

I have been working on implementing date validation for matDatepicker and have run into an issue where the error messages do not show up when the start date is set to be greater than the end date. The error messages are supposed to be displayed using inter ...

What is the best way to incorporate a conditional type into a function's return value when the return values have a connection?

I'm trying to understand the concept behind this code snippet. There is a function: export const useProject = (id: string) => { <project fetching logic here> return { project, loading: project === undefined } } In simple term ...

Quick tip: Adding a close 'X' button to an ng-bootstrap popover

As a newcomer to angular 5, I have been working on adding an 'x' button in the top right corner of a popover. Once this 'x' is clicked, the popover should be closed. Is there a way to achieve this using ng-bootstrap popover? Below is my ...

What is the process for importing a TypeScript module from the local directory?

I am currently working on a TypeScript module with plans to eventually release it on NPM. However, before publishing, I want to import the module into another project hosted locally for testing purposes. Both projects are written in TypeScript. The TypeSc ...

Setting up a new folder in the internal storage within a React Native Expo environment

In my React Native Expo project, I am utilizing two functions to store data in a JSON file and then save the file to internal storage. However, the code currently asks for permission to store inside a chosen folder, but does not create the "ProjectName" fo ...

What steps can be taken to resolve the TS5023 error that arises when including "allowImportingTsExtensions" in the tsconfig.json file?

While working on my React project, I've encountered a specific error that reads: Could not parse tsconfig.json. Please ensure it contains valid JSON syntax. Details: error TS5023: Unknown compiler option 'allowImportingTsExtensions'. I tr ...

Pausing in a NodeJS HTTP request listener until receiving another response before proceeding

Essentially, this is a web proxy. Within a request listener, I am creating another http request, reading its response, and passing it to the main response. But I have the challenge of needing to wait for the secondary request to complete before continuing. ...

Experimenting with a module reliant on two distinct services

I am facing an issue with a component that relies on a service to fetch data. The service also retrieves configurations from a static variable in the Configuration Service, but during Karma tests, the const variable is showing up as undefined. Although I ...

Angular's Not In operator can be used to filter out unwanted

As a newcomer to Angular, I am attempting to implement a basic if statement to verify that my property does not match one of 10 specific values. Is there a method or filter within enums or lists that can achieve this easily? public type: string; if(type = ...

What is the best way to integrate environment-specific configuration options into an AngularJS and Typescript project?

Currently, I am working on a project using AngularJS, Typescript, and VisualStudio. One of the key requirements for this project is to have a configuration file containing constants that control various settings such as REST API URLs and environment names. ...

Encountering issues with Proxy functionality in the latest versions of Angular 13 and Spring Boot

I've encountered an issue with the proxy configuration in Angular. I'm unsure if it's a problem within my Angular settings or if there's a configuration issue in Spring. For testing purposes, I have a backend built in springboot to han ...

Tips for implementing a request timeout in Typeorm/Typescript

Today, when using Typeorm with Postgres, there seems to be an issue where the behavior of getManager().query(...) getRepository().createQueryBuilder(...).getMany() is causing it to wait indefinitely for a response. Is there a way to set a timeout for t ...

When object signatures match exactly, TypeScript issues a warning

I am facing an issue with typescript while trying to use my own custom type from express' types. When I attempt to pass 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' as a parameter of type 'Context&a ...

Explore accessing TypeScript class properties within a JavaScript function

This is the code I have: export class CustomToast implements OnInit { toastTypeGroup: string; message: string; title: string; showDuration= "300"; constructor(_toastTypeGroup: string, _mess ...

Is there a way to apply a consistent style to all the fields of an object at once?

I have a formatting object named typography that includes various styles. One common issue I've encountered is that the line-height property is consistently set to 135%. Anticipating that this might change in the future, I am looking for a way to cent ...

Discovering all words enclosed by '#' in a string using React TypeScript

Trying to figure out how to extract words between '#' in a given string... For example: const str = `<Table striped bordered hover> <thead> <tr> <th>#project name#</th> <th>#First Name#& ...

Issues with replicating Typescript

Hey there, I'm encountering an issue with TypeScript. Here is the code snippet: class A { constructor() { this.initialize(); } public initialize() { console.log('a') } } class B extends A { constructor( ...

Error in React Typescript: No suitable index signature with parameter type 'string' was located on the specified type

I have encountered an issue while trying to dynamically add and remove form fields, particularly in assigning a value for an object property. The error message I received is as follows: Element implicitly has an 'any' type because expression o ...

Angular: a technique for creating customized error messages and modifying fields

When an error occurs in a form, the text fields are cleared and the errors are set as shown below switch(result){ case "SUCCESS": // handle success case case "ERROR1": this.Form.controls.text1.setValue(''); ...