简体   繁体   中英

How to write type safe assertion functions in TypeScript?

TypeScript 3.7 has this new cool feature which enables us to write "assertion functions". For example, here is one of mine:

export type TOfferAttrName = keyof typeof offerAttrMap;

export const assertIsOfferAttrName = (name: string): asserts name is TOfferAttrName => {
  if (!Object.prototype.hasOwnProperty.call(offerAttrMap, name)) {
    throw new Error('It is required that property name is an allowed one');
  }
};

The problem is that there is nothing forcing me to write a correct assertion function. I can pretty much just omit the whole body of the function and TS will be perfectly happy with it. Thus it is quite equal to just optimistically typecasting with as .

Am I missing something and is there a way for TS to actually force me to write a correct assertion function?

The idea of assertions (as with type guard) is that you as the programmer potentially something that TypeScript doesn't and that you want to make the type system aware of that.

So in a case where you know that something is always of type "X", using an assertion of assertIsT(obj: any): asserts obj is T {} is a perfectly valid point that you know that obj is definitely T and you want the compiler to know that, too.

So to speak, type guards and assert functions are an escape hatch that is just more elegant than casting and any-typing. The compiler won't check them, but believe you .

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