Sergey Sergey - 1 month ago 12
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;
}


markStepDone('anything');


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

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: https://github.com/Microsoft/TypeScript/pull/10425

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

Comments