I tried writing something like this.
console.log(Sever is runninng at ${hostname}:${port})
const s = serve({ port: 3001 });
const addr = s.listener.addr;
The result object is like this { hostname: "0.0.0.0", port: 3001, transport: "tcp" } but when accessing port gets following error.
error: TS2339 [ERROR]: Property 'port' does not exist on type 'Addr'.
Property 'port' does not exist on type 'UnixAddr'.
When trying to access path (which is in UnixAddr) it says below.
error: TS2339 [ERROR]: Property 'path' does not exist on type 'Addr'.
Property 'path' does not exist on type 'NetAddr'.
Hi, @dhanushkac,
I found this in the Typescript docs:
https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions
https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html?#discriminating-unions
So this is working for me:
switch (addr.transport) {
case "tcp":
case "udp":
console.log(`Sever is runninng at ${addr.hostname}:${addr.port}`);
break;
}
Typescript only allows accessing common members to all types in the union, in this case we can access only transport. Letting developers use type guards or even type casting to UnixAddr or NetAddr shouldn't be the preferred solution imo. It could be either provided as Deno.port() like it is (currently unstable) for Deno.hostname(), or it could be handled easily by adding an optional interface for UnixAddr and NetAddr and only letting transport be the required field (since that is already the only required field). I can make a PR for that. @bartlomieju
Hi, @dhanushkac,
I found this in the Typescript docs:
https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unionsSo this is working for me:
switch (addr.transport) { case "tcp": case "udp": console.log(`Sever is runninng at ${addr.hostname}:${addr.port}`); break; }
Thank you for your answer. I tried this. it also gives me the same result as posted.
A quick workaround:
(server.listener.addr as Deno.NetAddr).port!
(server.listener.addr as Deno.NetAddr).hostname!
A quick workaround:
(server.listener.addr as Deno.NetAddr).port! (server.listener.addr as Deno.NetAddr).hostname!
Yeah.. this is good! :)
Closing as resolved.
Most helpful comment
A quick workaround: