如何转换回调'Function'类型?



我在打字稿中使用'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可以是Functionstring,则可以使用联合类型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);
        }
    });
});

最新更新