我在打字稿中使用'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);
}
});
});
如何listener
投string
或正确的方法来获得string
?
如果参数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);
}
});
});