2

Is there a way to enforce the keys of an interface to be used from an array of strings:

E.g. If we have the following array:

const myArray = ['key1', 'key2'];

I would like to create a new interface called MyInterface that would force all myArray entries to be the keys of an object:

const myObj: MyInterface = {
  'key1': true,
  'key2': false,
}

1 Answer 1

6

You can use the keyof operator for exactly this purpose.

interface MyInterface {
  key1: boolean;
  key2: boolean;
}

const myObj: MyInterface = {
  key1: true,
  key2: false,
}

const myArray: Array<keyof MyInterface> = ['key1', 'key2'];
// or ...
const myOtherArray: Array<keyof typeof myObj> = ['key1', 'key2'];

You could also go backwards like so

const myArray = ['key1', 'key2'] as const;

type MyType = Record<typeof myArray[number], boolean>;

const myObj: MyType = {
  key1: true,
  key2: false,
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply. What is the [number] syntax in TypeScript?
You can learn more about this here @OvidijusParsiunas typescriptlang.org/docs/handbook/2/indexed-access-types.html
@emeraldsanto is there a way to have mixed value types? Some values are booleans, strings, etc
You can use "ReadonlyArray<keyof MyInterface>" if you need myArray as a const

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.