Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 属性在函数';s多个类型的返回值_Node.js_Typescript - Fatal编程技术网

Node.js 属性在函数';s多个类型的返回值

Node.js 属性在函数';s多个类型的返回值,node.js,typescript,Node.js,Typescript,我正在使用typescript编写NodeJS程序 在这个程序中,我导入了一个名为ts-md5的节点模块,其中有一个函数hashStr(),它可以返回string或Int32Array 我需要在我的程序中执行以下操作: Md5.hashStr(str).toUpperCase(); 但是,编译器会报告错误: error TS2339: Property 'toUpperCase' does not exist on type 'string | Int32Array'. 程序运行成功。因为它

我正在使用typescript编写NodeJS程序

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

我需要在我的程序中执行以下操作:

Md5.hashStr(str).toUpperCase();
但是,编译器会报告错误:

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

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

您可以使用类型保护或类型断言

类型防护装置

类型断言

let hash=(Md5.hashStr(str)).toUpperCase();
类型保护的好处是它在技术上更安全——因为如果您在运行时得到的不是字符串的东西,它仍然可以工作。类型断言只是您重写了编译器,因此从技术上讲并不安全,但它被完全删除,因此会产生与出错时相同的运行时代码。

hashStr
is
ts-md5
键入

static hashStr(str: string, raw?: boolean): string | Int32Array;
查看,当
raw
为true时,is似乎返回
Int32Array
,否则返回
string

考虑到该声明,使用类型断言再好不过了:

let hash = (Md5.hashStr(str) as string).toUpperCase()
表示返回类型依赖于TypeScript中的参数的正确方法是via。像这样的方法应该会奏效:

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...
}

我建议向ts-md5发布一个关于这一点的问题。

两种方法都有效,类型保护方法提供了一个安全的解决方案,我可以处理两种退货类型。非常详细和有用的解释。谢谢我接受另一个答案,因为它提供了一种处理这两种返回类型的方法,以避免运行时错误。
let hash = (Md5.hashStr(str) as string).toUpperCase()
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...
}