Home > Mobile >  TypeScript Suggested keys in object
TypeScript Suggested keys in object

Time:04-01

I would like to define a TypeScript type, which would suggest (preferred) object keys in editor, but I do not want to restrict user to define arbitrary keys.

So I have defined following type:

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

These are preferred properties: 'click' | 'change' | 'blur' (but I do want to allow arbitrary string.)

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

Now I want the editor to tell me about these: 'click' | 'change' | 'blur' in the first place.

Is it possible? Is my example correct? Visual Studio Code / enter image description here

CodePudding user response:

If you add | string to SuggestedProperties, then the entire type will be eagerly reduced to just string. All the string literal types will be absorbed in the union, and then the compiler and your IDE will have forgotten all about them:

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

Instead you should make your SuggestedKeysType a type with both known keys and a string index signature, possibly like this:

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

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

Then you get the suggestions you expect:

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

Playground link to code

CodePudding user response:

I dont know if exists any better solution but this way works:

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

autocomplete will suggest SuggestedProperties first and you will can pass any other property

  • Related