Seph Reed
Seph Reed

Reputation: 10878

How can I make a Typescript interface which type checks some properties, but also allows any prorperty?

I have some Typescript interface which has some properties defined, but can also be treated as an any object

interface IBob {
  makesBurgers?: boolean;
  hasRestaurant?: boolean;
  [key: string]: any;  // whatever other properties someone wants to thow at it
}

The code above compiles just fine, but it does not type check for makeBurgers to be a boolean. The following code shows no errors:

const Bob: IBob = {};
Bob.makesBurgers = "sure"; // would be nice if this was an error, but it isn't

How can I make an interface which typechecks as much as possible, without defining every single property it could ever have?

EDIT: It appears that some ts-lint, in some instances, does not catch this error, while in the more up-to-date playground it does. This is an issue with older versions of ts-lint, and the solution is to update.

Upvotes: 0

Views: 40

Answers (1)

Fathy
Fathy

Reputation: 5199

The type-checker should throw an error for this (it does on TypeScript 2.6). You IDE seems to be the problem, you should probably check you are on the right version or reinstall.

Please note this should have nothing to do with tslint. tslint adds more diagnostics, it should not remove any TypeScript diagnostics unless there is a bug on your IDE tslint plugin.

Upvotes: 2

Related Questions