Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: What is type URL?

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

like image 976
user130685 Avatar asked Jul 05 '16 07:07

user130685


People also ask

What is type in TypeScript?

What is a type in TypeScript. In TypeScript, a type is a convenient way to refer to the different properties and functions that a value has. A value is anything that you can assign to a variable e.g., a number, a string, an array, an object, and a function.

What is type alias in TypeScript?

In Typescript, Type aliases give a type a new name. They are similar to interfaces in that they can be used to name primitives and any other kinds that you'd have to define by hand otherwise. Aliasing doesn't truly create a new type; instead, it gives that type a new name.

What is URL in JavaScript?

URL() The URL() constructor returns a newly created URL object representing the URL defined by the parameters. If the given base URL or the resulting URL are not valid URLs, the JavaScript TypeError exception is thrown. Note: This feature is available in Web Workers.

What is a URL object?

The vanilla JavaScript URL object is used to parse, construct, normalize, and encode URLs. It provides static methods and properties to easily read and modify different components of the URL.


1 Answers

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.

like image 164
Spiralis Avatar answered Oct 28 '22 12:10

Spiralis