2016-07-05 300 views
4

我想確保string類型的接口成員是一個正式的有效URL。我可以將成員聲明爲URL,但我無法爲其分配一個有效URL的字符串。Typescript:什麼是類型URL?

interface test { 
    myurl: URL; 
} 

var a : test; 
a.myurl = "http://www.google.ch" 

編譯時,我得到:

類型 '串' 是不能分配給鍵入 'URL'。

我是否必須爲我的任務使用裝飾器(https://www.typescriptlang.org/docs/handbook/decorators.html)?

什麼是URL好?

我用的打字稿1.8.10

回答

5

AFAICT,網址是打字稿「內置」功能的基礎上,WhatWG Url specifications。鏈接到頁面既有理由又有示例。

總之,它提供了一種使用url的結構化方式,同時確保它們是有效的。它會在嘗試創建無效的URL時拋出錯誤。

打字稿有根據類型定義設置如下(以打字稿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找到。