gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
i have enum: enum Test { A, B, C, D } and dictionary: const dict = { [Test.A] = 1,…
- User
i have enum: enum Test { A, B, C, D }
and dictionary: const dict = { [Test.A] = 1, [Test.B] = 2, [Test.C] = 3 }
write function where in parameters we can pass only dict keys using typescript
- Assistant
To create a TypeScript function where you can pass only the keys of the
dictas parameters, you'll first need to ensure that the keys are typed correctly. Here's how you can achieve this:- Define the enum
Test. - Define the dictionary
dictusing the enum members as keys. - Create a function that only accepts the keys of
dictas valid parameters.
Here is a complete example:
// Define the enum enum Test { A, B, C, D } // Define the dictionary using the enum members as keys const dict: Record<Test, number> = { [Test.A]: 1, [Test.B]: 2, [Test.C]: 3 }; // Define a type that extracts the keys of the dict type DictKeys = keyof typeof dict; // Function that accepts only keys of the dict function processDictKey(key: DictKeys) { console.log(`The value for key ${Test[key]} is ${dict[key]}`); } // Example usage: processDictKey(Test.A); // Valid processDictKey(Test.B); // Valid processDictKey(Test.C); // Valid // processDictKey(Test.D); // Error: Argument of type 'Test.D' is not assignable to parameter of type 'DictKeys'. - Define the enum