Typescript: security type for interface properties in function declaration

Let's say we have such a simple example:

interface Steps { stepOne?: boolean; stepTwo?: boolean; stepThree?: boolean; } let steps: Steps = {}; function markStepDone (step: ???) { steps[step] = true; } markStepDone('anything'); 

How can I stop him from passing β€œanything” to this function and allow only ['stepOne', 'stepTwo', 'stepThree']?

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

+5
source share
1 answer

What you are looking for is the keyof operator, which is being implemented this week (yes, really). It will look like this:

 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

Meanwhile, string is a rough approximation, or handwritten type "stepOne" | "stepTwo" | "stepThree" "stepOne" | "stepTwo" | "stepThree" "stepOne" | "stepTwo" | "stepThree" will give you the exact behavior of keyof Steps

+8
source

Source: https://habr.com/ru/post/1258756/


All Articles