Sergey Sergey - 1 year ago 120
TypeScript Question

Typescript: type safety for interface properties in a function declaration

Let's say we have this simple example:

interface Steps {
stepOne?: boolean;
stepTwo?: boolean;
stepThree?: boolean;

let steps: Steps = {};

function markStepDone (step: ???) {
steps[step] = true;


How can I prevent it from allowing to pass 'anything' to this function and allow only ['stepOne', 'stepTwo', 'stepThree']?

I also tried to do it with enum, but turned out that you cannot use enum as an index signature...

Answer Source

What you're looking for is the keyof operator, which is being implemented this week (yes, really). It will look like this once it's ready:

function markStepDone (step: keyof Steps) {
  steps[step] = true;

An early PR with a different name (keysof) is here:

In the meantime, string is a rough approximation, or the hand-written type "stepOne" | "stepTwo" | "stepThree" will give you the exact behavior of keyof Steps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download