简体   繁体   中英

Property 'host' does not exist on type 'ProxyTargetUrl' Error. Even though i get IntelliSense in JS File

I have the following code in a .ts file:

const connection = {
        host: options.target.host
      };

options are of type httpProxy.ServerOptions and target is of type ProxyTargetUrl

The error i get is the following:

Property 'host' does not exist on type 'ProxyTargetUrl'.
  Property 'host' does not exist on type 'string'.

These options are part from the http-proxy npm module. The newest typings are installed. "@types/http-proxy": "^1.16.2"

When i follow the declaration i see this:

type ProxyTargetUrl = string | url.Url;

--

interface Url extends UrlObjectCommon {
        port?: string;
        query?: string | null | ParsedUrlQuery;
    }

--

interface UrlObjectCommon {
        auth?: string;
        hash?: string;
        host?: string;
        hostname?: string;
        href?: string;
        path?: string;
        pathname?: string;
        protocol?: string;
        search?: string;
        slashes?: boolean;
    }

Why do i get this error? When i copy my code over in a JS File i get IntelliSense for the host property and the code also works perfectly fine at runtime. So the typings are correct. What did i miss?

The problem is that in your union type type ProxyTargetUrl = string | url.Url type ProxyTargetUrl = string | url.Url , only Url has field host defined.

To access this field, you would need a type assertion: (<Url>options.target).host .

See this Github issue for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM