【问题标题】:Typescript: What is type URL?打字稿:什么是类型 URL?
【发布时间】:2016-11-06 21:59:57
【问题描述】:

我想确保字符串类型的接口成员是正式有效的 URL。我可以将成员声明为 URL,但我不能为其分配一个有效 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

【问题讨论】:

    标签: typescript1.8


    【解决方案1】:

    AFAICT,URL 是基于 WhatWG Url specifications 的打字稿“内置”功能。链接到页面既有理由又有例子。

    简而言之,它提供了一种使用 url 的结构化方式,同时确保它们是有效的。尝试创建无效 url 时会抛出错误。

    Typescript 具有如下设置的相应类型定义(从 typescript 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找到。

    【讨论】:

      猜你喜欢
      • 2022-11-04
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2019-01-26
      • 1970-01-01
      • 2020-05-31
      • 2021-03-14
      相关资源
      最近更新 更多