我想确保string类型的接口成员是一个正式有效的URL。我可以将成员声明为URL,但我不能为其分配一个有效URL的字符串。
interface test {
myurl: URL;
}
var a : test;
a.myurl = "http://www.google.ch"
编译时我得到:
类型'string'不能指定为'URL'类型。
我是否必须为我的任务使用装饰器(https://www.typescriptlang.org/docs/handbook/decorators.html)?
什么是网址?
我正在使用typescript 1.8.10
答案 0 :(得分:15)
AFAICT,URL是基于WhatWG Url specifications的打字稿“内置”功能。链接到页面既有基本原理,也有示例。
简而言之,它提供了一种使用网址的结构化方式,同时确保它们有效。尝试创建无效网址时会抛出错误。
Typescript具有如下设置的相应类型定义(从typecript 2.1.5开始):在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;
}
对于您的用例,您应该能够像这样使用它:
a.myurl = new URL("http://www.google.ch");
可以在WhatWG Url specifications中找到更多构造函数,示例和解释。