如何投射回调'功能'类型?

时间:2016-04-27 14:48:00

标签: node.js typescript

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

我知道,如果response.setEncoding然后调用response.on,我会收到'string'的回调。所以我尝试施放'字符串'。但是我收到错误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);
        }
    });
});

如何将listener投射到string或以正确的方式获取string

1 个答案:

答案 0 :(得分:1)

如果参数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);
        }
    });
});