Suggestions for keys in TypeScript objects

I am looking to create a TypeScript type that will suggest certain object keys in the editor, while still allowing users to define arbitrary keys if they wish. Here is the type I have defined:

type SuggestedProperties = 'click' | 'change' | 'blur' | string;

The preferred properties are: 'click' | 'change' | 'blur' (but I want to allow any string as well).

type SuggestedKeysType = Partial<{ [key in SuggestedProperties]: any }>;

Now my goal is for the editor to automatically list these keys: 'click' | 'change' | 'blur' when working with this code.

Is this achievable? Is my example accurate? Tested on Visual Studio Code / stackblitz:

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

Answer №1

When you append | string to SuggestedProperties, it causes the entire type to be immediately reduced to just string. This results in all the string literal types being merged into a union, leading the compiler and your IDE to no longer recognize them:

type Oops = 'a' | 'b' | string;
// type Oops = string

Instead, it is recommended to define your SuggestedKeysType as a type with both specified keys and a string index signature, possibly like this:

type SuggestedProperties = 'click' | 'change' | 'blur';

type SuggestedKeysType = { [K in SuggestedProperties]?: any } & { [k: string]: any }

By following this approach, you will receive the expected suggestions:

const myObject: SuggestedKeysType = {
  foo: 1,
  bar: 2,
  click: 3,
  // Suggestions here:
  // ☐ blur, (property) blur?: any
  // ☐ change, (property) change?: any
}

Link to code in Playground

Answer №2

I'm not sure if there is a superior solution, but this method seems to work:

type MyObj = Partial<
  {
    [key in SuggestedProperties]: any;
  } & {
    [index: string]: any;
  }
>;

When using autocomplete, SuggestedProperties will be suggested first and you can pass any other property as needed.

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

Showcasing an input field once a specific button is pressed in an Angular application

When triggered, I am looking for a blank panel that will display a text box within the same panel. This functionality should be implemented using Angular. ...

What is the best approach to repurpose a jest test for various implementations of a shared interface?

I'm facing a challenge: describe("Given a config repository", () => { let target: ConfigRepository; beforeEach(() => { target = InMemoryConfigRepository(); }); test("When creating a new config, Then it is ...

Angular utilizes boolean variables to determine if an attribute is required

Hey there! I'm currently working on a project where I need to make an input form field required or optional based on the value of a boolean variable in my component. This is what my component looks like: public showField: boolean = true; Here' ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

Utilizing Angular 2 to Access APIs with Basic Security Authentication

I am attempting to make a call to an HTTP method implemented with ASP Web API from an Angular 2 client. However, I am encountering the following error: OPTIONS 401 (Unauthorized) XMLHttpRequest cannot load . The response to the preflight request does no ...

The error message for Angular FormControl's minimum length validation is not showing up in the errors

My goal is to access the minlength error, but when I check all the errors, it's not there. Below is my form control title: new FormControl("", [Validators.minLength(10), Validators.required]), I expect to see both the required and minlengt ...

To collapse a div in an HTML Angular environment, the button must be clicked twice

A series of divs in my code are currently grouped together with expand and collapse functionality. It works well, except for the fact that I have to click a button twice in order to open another div. Initially, the first click only collapses the first div. ...

Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these ...

Combining Typescript interfaces to enhance the specificity of a property within an external library's interface

I have encountered a scenario where I am utilizing a function from an external library. This function returns an object with a property typed as number. However, based on my data analysis, I know that this property actually represents an union of 1 | 2. Ho ...

Typescript error encountered when executing multiple API calls in a loop causing Internal Server Error

I'm relatively new to Typescript/Javascript and I am working on a function called setBias(). In this function, I want to set all indices of this.articles[i].result equal to the biased rating returned by the function getBiasedRating(this.articles[i].ur ...

How to customize the radio button style in Angular 11 by changing the text color

Hey guys, I'm working with these radio buttons and have a few questions: <form [formGroup]="myForm" class="location_filter"> <label style="font-weight: 500; color: #C0C0C0">Select a button: </label& ...

The joinAndSelect function in NestJS is having trouble fetching all the data from the PostgreSQL database

In my database, I have three tables named product, branch, and product_branches. The product table contains columns: id, name The branch table contains columns: id, name, lat, lng And the product_branches table contains columns: productId, branchId I w ...

There is no corresponding index signature for type 'string' in Type

This is the code snippet I am using as a reference: const MyArray = [ { name: "Alice", age: 15 }, { name: "Bob", age: 23 }, { name: "Eve", age: 38 }, ]; type Name = typeof MyArray[string]["name"]; //throws err ...

How can you display a loading indicator after a delay using Observables, but make sure to cancel it if the loading is completed

Within my customer-detail component, I have implemented code that achieves the desired outcome. However, I believe there might be a more reactive and observable way to approach this task. Instead of using an if statement to set this.isLoading = true;, is ...

Error: The version of @ionic-native/[email protected] is not compatible with its sibling packages' peerDependencies

When attempting ionic cordova build android --prod, the following error occurred: I have tried this multiple times. rm -rf node_modules/ rm -rf platforms/ rm -rf plugins/ I deleted package.lock.json and ran npm i, but no luck so far. Any ideas? Er ...

React.js TypeScript Error: Property 'toLowerCase' cannot be used on type 'never'

In my ReactJS project with TSX, I encountered an issue while trying to filter data using multiple key values. The main component Cards.tsx is the parent, and the child component is ShipmentCard.tsx. The error message I'm receiving is 'Property &a ...

What is the best way to transfer information from the window method to the data function in a Vue.js application?

Is there a way to transfer information from the window method to the data function in a vuejs component? Take a look at my window method: window.authenticate = function(pid, receiptKey) { console.log("Authentication"); console.log(this) localStorag ...

What practical applications exist for preserving JSX post-transpilation of a tsx file?

While troubleshooting another issue, I decided to delve into Typescript's documentation on JSX usage. I discovered that some options involve converting JSX while others do not. I am puzzled as to why one would need to preserve JSX in transpiled file ...

What is the best way to connect my Typescript NextJS code to my Express API?

My goal is to extract data from my API, which is providing the following JSON: [ { project: "Challenges_jschallenger.com" }, { project: "Using-Studio-Ghilis-API-With-JS-Only" }, { project: "my-portfolio-next" }, { proj ...

Solving CORS policy error in a MEAN stack application deployed on Heroku

I've been grappling with a CORS policy error in my MEAN stack app for quite some time now. The specific error message I keep encountering is: "Access to XMLHTTPRequest at <my heroku app url.com/login> from origin has been blocked by CORS ...