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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With