5

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...

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Until keyof is out I ended up doing something like this: type AllSteps = 'stepOne' | 'stepTwo' | 'stepThree'; interface Steps { [index: string]: boolean; } function markStepDone (step: AllSteps) {

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.