属性在函数的多个types的返回值上不存在

我正在使用打字稿来编写NodeJS程序。

在这个程序中,我导入一个名为ts-md5的节点模块,其中有一个函数hashStr() ,它可以返回一个string值或Int32Array

我需要在我的程序中做这样的事情:

 Md5.hashStr(str).toUpperCase(); 

但是,编译器抱怨错误:

 error TS2339: Property 'toUpperCase' does not exist on type 'string | Int32Array'. 

程序运行成功。 因为它在运行时总是返回string 。 但是我想知道是否有办法摆脱这个恼人的错误?

您可以使用types警戒或types断言。

types的后卫

 let hash = Md5.hashStr(str); if (typeof hash === 'string') { hash = hash.toUpperCase(); } 

键入断言

 let hash = (<string>Md5.hashStr(str)).toUpperCase(); 

types守卫的好处是它在技术上更安全 – 因为如果你在运行时得到的东西不是string,它仍然可以工作。 types声明只是你重写了编译器,所以它在技术上不是安全的,但是它被完全擦除,因此导致在你有错误的地方有相同的运行时代码。

hashStrts-md5 hashStr中声明为

 static hashStr(str: string, raw?: boolean): string | Int32Array; 

看看这个实现 ,似乎是在raw为true时返回Int32Array ,否则返回string

鉴于这个声明,你不能比使用types断言更好:

 let hash = (Md5.hashStr(str) as string).toUpperCase() 

expression该返回types的正确方法取决于TypeScript中的参数是通过重载声明 。 像这样的东西应该工作:

 static hashStr(str: string): string; static hashStr(str: string, raw: false): string; static hashStr(str: string, raw: true): Int32Array; static hashStr(str: string, raw: boolean): Int32Array | string; static hashStr(str: string, raw?: boolean): string | Int32Array { // implementation goes here... } 

我build议张贴与ts-md5关于这个问题。