51

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

1 Answer 1

70

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.

Sign up to request clarification or add additional context in comments.

1 Comment

For me, I can't use URL.canParse(). It is a static method in the WhatWG URL specifications. But TypeScript has not defined it yet. Or perhaps I'm misconfiguring my compilerOptions somehow in tsconfig.json?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.