简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM