Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: type safety for interface properties in a function declaration

Tags:

typescript

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

like image 847
Sergey Avatar asked Oct 25 '16 14:10

Sergey


People also ask

Can a function implement an interface TypeScript?

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.

What is the type of an interface TypeScript?

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.

Can you restrict TypeScript object to contain only properties defined by its class?

Typescript can't restrict extra properties Unfortunately this isn't currently possible in Typescript, and somewhat contradicts the shape nature of TS type checking.

How do you pass an interface as a parameter TypeScript?

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.


1 Answers

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

like image 187
Ryan Cavanaugh Avatar answered Nov 15 '22 07:11

Ryan Cavanaugh