0

In this demo there are two objects. KEYS and KEYS2. If we import KEYS in index.ts we get autocomplete for K1 and K2 because KEYS does not implement an interface.

With KEYS2 we don't because it implements an interface.

This is the stackblitz.

export interface IKeyObject {
  [key:string]: IKeyValue | any
} 

export interface IKeyValue {
  key:string
  value:any
}

export const KEYS = {
  K1: 'K1',
  K2: 'K2'
}

export const KEYS2:IKeyObject = {
  K1: { key:'', value:''},
  K2: {key:'', value:''}
}

Is there a way to implement the interface and get autocomplete for the keys on the object at the same time?

So in other words if we import KEYS2, and us it in a constructor:

constructor() {
    const v = KEYS.
}

VSCode will give us the properties on the object as autocomplete values?  


1 Answer 1

2

Make your KEYS an enum and your IKeyObject a Record and things should work

The only type issue left is that you are using IKeyValue | any which is effectively just any.

export enum KEYS {
  K1 = "K1",
  K2 = "K2"
}
export type IKeyObject = Record<KEYS, IKeyValue | any>;

export interface IKeyValue {
  key: string;
  value: any;
}

export const KEYS2: IKeyObject = {
  K1: { key: "", value: "" },
  K2: { key: "", value: "" }
};

You should now be able to have autocomplete on KEYS2 to show K1 and K2 as options, though you'll have to remove any from IKeyObject to get more autocomplete.

Stackblitz Example with everything I mentioned and removing any.

Sign up to request clarification or add additional context in comments.

2 Comments

enum KEYS... can be replaced by type KEYS = 'K1' | 'K2';. But the idea is correct.
You can't if you want to be able access KEYS like it's both a type and a value, which is what is currently being done in Ole's code. Using a string enum for this can be better because of that feature.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.