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...
TypeScript Interface can be utilized to implement a type in the class after it defines it. TypeScript Interface can be used to define a function type by ensuring a function signature. We use the optional property using a question mark before the property name colon.
TypeScript Interface Type TypeScript allows you to specifically type an object using an interface that can be reused by multiple objects. To create an interface, use the interface keyword followed by the interface name and the typed object.
Typescript can't restrict extra properties Unfortunately this isn't currently possible in Typescript, and somewhat contradicts the shape nature of TS type checking.
An interface type cannot be passed as a parameter. When running TypeScript code, you are really compiling it down to JavaScript and then running the JavaScript. An interface is a TypeScript compile-time construct, so at runtime, there is no such thing as an interface type to call functions on or inspect properties of.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With