Is it possible for me to utilize `keyof` in Typescript in order to accurately define the properties I wish to retrieve from this specific type?

Consider a scenario where I have a query class and an execute method structured as follows:

class Query {
    name: string;
    sql: string;
} 

function execute(query: Query): any{
    let retVal = {};
    retVal[query.name] = true;
    return retVal;
}

q = new Query();
q.name = "thisIsMyQueryName";
let result = execute(q); // Returns: {thisIsMyQueryName: true}
// the typeof result is still 'any', but ideally, it should be:
// {thisIsMyQueryName: boolean}

In this case, the object being returned holds a shape that mirrors the instance of the class passed into it. Since the query's "name" can vary at runtime, there is no way to inform the compiler about the presence of a property called "thisIsMyQueryName" in the returned object.

However, I've been exploring methods to enhance static analysis. Although we have multiple query objects with known names during instantiation, achieving full static analysis seems challenging. Experimenting with different approaches involving key of has shown some potential, but a satisfactory solution remains elusive.

It would be ideal if something like this were possible:

let q = {
   sql: "",
   queryName: {
       thisIsMyQueryName: ""
   }
}
let result = execute(q); // Returns: {thisIsMyQueryName: true}
// typeof result == {thisIsMyQueryName: boolean}

While I understand the impossibility of the above code snippet, I believe there must be a way to describe these instances so that the compiler recognizes the presence of a property named keyof q.queryName.

Any suggestions or insights?

Answer №1

To achieve this, define .queryName as a type parameter and employ keyof on that particular parameter:

class Query<TName> {
    queryName: TName
    sql: string;
} 
type Result<TName> = {
    [P in keyof TName]: boolean
}

function execute<TName>(query: Query<TName>): Result<TName> {
    return { [Object.keys(query.queryName)[0]]: true };
}

const q = {
    sql: "",
    queryName: {
        thisIsMyQueryName: ""
    }
};

const result = execute(q);
const b = result.thisIsMyQueryName; // boolean

Interactive example.

Nonetheless, the function cannot be reliably implemented.

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

Create a TypeScript variable that has a type definition allowing for the inclusion of null

I am dealing with the type definition below, which was created by a framework: export type SecretCategory = { 'Password' : null } | { 'Note' : null } | { 'Document' : null }; What is the best way to declare a variable of type ...

Are there any alternatives to ui-ace specifically designed for Angular 2?

I am currently working on an Angular2 project and I'm looking to display my JSON data in an editor. Previously, while working with AngularJS, I was able to achieve this using ui-ace. Here is an example of how I did it: <textarea ui-ace="{ us ...

What is the ideal timing to incorporate an error handler in an Observable?

I find myself uncertain about the best practices for error handling in general. For instance, if I'm already handling errors in my service using catchError, is it necessary to also include an error handler in my subscription? Here's an example o ...

Leveraging the 'ref' keyword in TypeScript with Next.js

Currently, I am learning TypeScript in React but encountered a warning. import {useref} from 'react' export default function test(){ cons tmp = useRef() const data = tmp.current?.value return ( <div> <input type = ...

Executing a method from a callback within the data() function in Vue 2.7 – Here's how!

This component uses a third-party module known as HelloWorld. This module has a prop called closeCallbacks, which is an array of callbacks that are triggered when the HelloWorld component is closed. Unfortunately, the functionality of the third-party comp ...

Angular modules are designed to repeat chunks of code in a

Whenever I scroll the page, my function pushes items to an array. However, I am facing an issue where the pushed items are repeating instead of adding new ones. Solution Attempt onScroll(): void { console.log('scrolled'); var i,j,newA ...

Warning from Firebase CLI deployment: The Node.js 8 runtime has been marked as deprecated and is scheduled to be phased out by 2020-12-05

Attempting to deploy TypeScript onto my FCF isn't working as expected based on the documentation and official Firecasts video. When deploying the default code (helloworld) instead of TypeScript, it deploys a node.js file which is confusing. Below are ...

In the scenario where I have a nested readonly array within an object, what is the best way to duplicate that object and transform the array to allow for mutations (such as inserting into Akita)?

Suppose I have the following TypeScript interface: interface Member { readonly id: number; readonly name: string; readonly email: string; groups: <ReadonlyArray>Group } interface Group { readonly id: number; readonly name: string; ...

Sending data to the server using AngularJS 1.x and Typescript

I am encountering an issue where the header values I'm trying to post to the server are not properly embedded in the request header, resulting in incorrect answers. I understand that there is a mistake in my approach, but I can't seem to pinpoint ...

Angular 2 forms are displaying ngvalid when input fields are marked as nginvalid

The form displays ngvalid because I have included the code like this: <form novalidate class="pop-form" (submit)="signUp()" #regForm="ngForm"> <div class="group"> <input type="text" [(ngModel)]="signUpData.name" [ngMode ...

How can one obtain the alphabet letters of a specific language?

Is there a way to programmatically retrieve the alphabet of a language (using its 2-letter ISO code) from an open-source repository? For instance: console.log(getAlphabet('en')); would result in: a b c d ... while console.log(getAlphabet(&apos ...

There is no such thing as Magic Sequelize Function

I am new to TypeScript and have recently started learning about the Sequelize ORM model. While I had worked on a few projects with Sequelize using plain JavaScript before, I decided to give it a shot with TypeScript this time. However, I've been facin ...

Is it feasible to incorporate a multi-level navigation menu into the "NavItem" component using MaterialUI with TypeScript?

Instructions for creating a multi-level navigation menu using MaterialUI and TypeScript: To the existing '/questions' section, it is desired to include the following 2 navigation menus: /questions/Tags /questions/Users This should resemble the ...

How can I preserve data in editable PDFs with Angular and JavaScript?

Need help with savedoc() functionality <iframe [src] ="fileurl" #iframe> </iframe> <button (click)="saveDoc()"> </button> Having trouble accessing edited PDF content in Typescript: /*api cal ...

The android() method could not be located on the root project 'xyz' of type org.gradle.api.Project when passing [before_plugins_] as arguments

Encountering an issue while attempting to run the Nativescript Android application on my device. The error message states: Could not find method android() for arguments [before_plugins_d5qrcua3za3scd760qug60fz6$_run_closure1@5754ca71] on root project &apos ...

Issue with updating BehaviorSubject not being reflected when called from my service component has been identified

In my HomeComponent, I am currently using *ngIf to switch between 3 components. The focus right now is on the relationship between two of them - the ProductListComponent and the ProductDetailComponent. Inside the ProductListComponent, there is a ProductLis ...

I seem to be missing something: Unhandled Rejection (TypeError): setToken function is not recognized

I am a beginner in React and TypeScript and I am facing an issue while trying to implement a basic functionality. Unfortunately, I keep encountering the error: Unhandled Rejection (TypeError): setToken is not a function. Can anyone provide me with some gui ...

Is it possible to implement pagination on a material table in Angular 10 without relying on the MatTableDataSource component?

How can I implement material pagination on a table without using MatTableDataSource? Most tutorials and examples I find online recommend the use of MatTableDataSource, but I'm unsure of how to actually utilize it. I am fetching data from a database ta ...

Posting a request in NativeScript using body form-data

Looking to send a JSON object to a login post URL similar to the format shown in the screenshot from Postman. The user object must match this format exactly for a successful login; otherwise, the API response indicates that the user object is not found. I ...

Discover the inverse of Object Arrays interaction in TypeScript

My agent object has the following structure: agentObj = { "agentId": "saqib", "attributes": [ { "name": "Marketing", "type": "Boolean", }, { "name": "English", "type": "Profi ...