我在打字稿中使用'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
?
答案 0 :(得分:1)
如果参数listener
可以是Function
或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);
}
});
});