简体   繁体   English

如何在 TypeScript 中编写类型安全的断言函数?

[英]How to write type safe assertion functions in TypeScript?

TypeScript 3.7 has this new cool feature which enables us to write "assertion functions". TypeScript 3.7 有这个很酷的新特性,它使我们能够编写“断言函数”。 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.我几乎可以省略整个函数体,TS 会非常满意。 Thus it is quite equal to just optimistically typecasting with as .因此,它完全等同于使用as乐观地进行类型转换。

Am I missing something and is there a way for TS to actually force me to write a correct assertion function?我是否遗漏了什么,TS 有没有办法真正强迫我编写正确的断言函数?

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.断言(与类型保护一样)的想法是,作为程序员的您可能有一些 TypeScript 没有的东西,并且您想让类型系统意识到这一点。

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.因此,在知道某物始终是“X”类型的情况下,使用assertIsT(obj: any): asserts obj is T {}是一个完全有效的点,您知道 obj 绝对是 T并且您想要编译器也知道。

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 .编译器不会检查它们,但相信

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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