I'm looking some way to type the testArray to ensure that only keys from the dict example can be set in the array.
enum example {
key1 = 'A',
key2 = 2,
key3 = '3',
};
const testArray: ?? = [example.key1, example.key2]; // Valid
const testArray: ?? = [example.key1, 'other']; // Invalid
I want ensure that only keys of example dict can be added to the testArray this way.
CodePudding user response:
You probably want something like this:
let example = {
key1: 'A',
key2: 2,
key3: '3',
} as const;
type ExampleValueArray = typeof example[keyof typeof example][]
const testArray: ExampleValueArray = [example.key1, example.key2]; // Valid
const testArray2: ExampleValueArray = [example.key1, 'other']; // Invalid
CodePudding user response:
If you want that only the keys present in example to be present in an array you can use this
let example = {
key1: 'A',
key2: B,
key3: '3',
};
export const testArray: (keyof typeof example)[];
Note that this will allow for multiple entries for key1
, key2
, etc.
If you want the values then you can use this
let example = {
key1: 'A',
key2: 'B',
key3: '3',
} as const;
const a: ((typeof example)[keyof typeof example])[];