如何转换回调“函数”类型?

延罗

我在打字稿中使用“ http”节点模块。

我知道,如果response.setEncoding再调用response.on,我会收到带有“字符串”的回调。因此,我尝试投射“字符串”。但是我有错误TS2352: Neither type 'Function' nor type 'string' is assignable to the other.

像这样

import * as http from "http";
import {IncomingMessage} from "http";

http.get("http://example.com", (response: IncomingMessage) => {
    response.setEncoding("utf8");
    response.on("data", (listener: Function) => {
        if (typeof listener === "string") {
            let matchArray: RegExpMatchArray = (listener as string).match(/a/g); // TS2352: Neither type 'Function' nor type 'string' is assignable to the other.
            console.log(matchArray);
        }
    });
});

如何投listenerstring或适当的方式来获得string

如果参数listener可以是aFunction或a string,则可以使用联合类型声明它Function|string

import * as http from "http";
import {IncomingMessage} from "http";

http.get("http://example.com", (response: IncomingMessage) => {
    response.setEncoding("utf8");
    response.on("data", (listener: Function|string) => {
        if (typeof listener === "string") {
            let matchArray: RegExpMatchArray = listener.match(/a/g);
            console.log(matchArray);
        }
    });
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何转换函数类型?

Golang:将接口转换回其原始类型

我如何将reflect.New的返回值转换回原始类型

类型转换/回调函数

将std函数对象转换回函子结构

如何将由statsmodels的VAR函数拟合的对数差异数据转换回实际值

大熊猫的行程将列的类型更改为浮动。如何将其转换回原始类型?

将GameObject转换回通用类型<T>

从对象类型转换回自定义对象并改进代码

如何将一串数字转换回二进制十六进制(\ x值)类型?

如何指定回调函数的类型?

如何通过函数的空指针参数传递int值并将其转换回int值?

将Javascript数组转换回JQuery类型的对象

如何根据参数类型转换函数的返回类型?

如何将mongodb go驱动程序的native.Timestamp类型转换回Golang time.Time类型?

如何从位集转换回int

PHP函数将html实体转换回html特殊字符

以匿名类型作为泛型参数的泛型类型实例,如何正确转换回原始类型?

将(原始类型)的类型转换回OCaml中的原始类型

预备替换回调

为何编译器无法转换回调?

如何将转换为字符串值的[[String]]转换回原始类型[[String]]?

使用可变参数参数将函数转换回原始签名

如何在不转换回基类类型的情况下以其派生类型返回对象?

如何转换为传递给函数的类型?

如何转换回调结果?

我如何使用一揽子 Into trait 实现来转换回原始类型?

如何正确抽象类型转换函数?

如何将 DurationFormatUtils 转换回毫秒