Typescript: What is type URL?

41,199

AFAICT, URL is a typescript "built-in" feature, based on the WhatWG Url specifications. The linked to page has both rationale and examples.

In short it offers a structured way of using urls while making sure that they are valid. It will throw errors when attempting to create invalid urls.

Typescript has the according type-definitions set as follows (as of typescript 2.1.5): in node_modules/typescript/lib/lib.es6.d.ts:

interface URL {
    hash: string;
    host: string;
    hostname: string;
    href: string;
    readonly origin: string;
    password: string;
    pathname: string;
    port: string;
    protocol: string;
    search: string;
    username: string;
    toString(): string;
}

declare var URL: {
    prototype: URL;
    new(url: string, base?: string): URL;
    createObjectURL(object: any, options?: ObjectURLOptions): string;
    revokeObjectURL(url: string): void;
}

For your use-case you should be able to use it like this:

a.myurl = new URL("http://www.google.ch");

More constructors, samples and explanations can be found in the WhatWG Url specifications.

Share:
41,199
user130685
Author by

user130685

I am a total idiot.

Updated on July 09, 2022

Comments

  • user130685
    user130685 almost 2 years

    I want to make sure that an interface member of type string is a formally valid URL. I could declare a member as URL but I cannot assign it a string that is a valid URL.

    interface test {
        myurl: URL;
    }
    
    var a : test;
    a.myurl = "http://www.google.ch"
    

    When compiling I get:

    Type 'string' is not assignable to type 'URL'.

    Do I have to use decorators for my task (https://www.typescriptlang.org/docs/handbook/decorators.html)?

    And what is URL good for?

    I am using typescript 1.8.10