我在打字稿中使用“ 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
可以是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] 删除。
我来说两句