Reputation: 773
I'm using 'http' node module in typescript.
I know, if response.setEncoding
then call response.on
, I got callback with 'string'. so I try to cast 'string'. But I got error TS2352: Neither type 'Function' nor type 'string' is assignable to the other.
like this
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);
}
});
});
How to cast listener
to string
or proper way to get string
?
Upvotes: 0
Views: 719
Reputation: 23712
If the parameter listener
can be a Function
or a string
, then it could be declared with an union type 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);
}
});
});
Upvotes: 1