转换对象键

时间:2016-09-10 20:17:33

标签: typescript

尝试转换密钥

import { Url, parse } from "url";
export class HalJson {
    _links: Links;
}

export class HalLinks implements Links {
    toUrl( rel: string ): Url {
        let link = <Link> this[rel];
        return parse( link.href );
    }
    [text: string]: Link;
}

export interface Links {
    [text: string]: Link;
    toUrl( rel : string ) : Url;
}

export interface Link {
    href: string;
}

但我收到此错误

[default] C:\Users\xeno\IdeaProjects\rpf-ui\src\util\Hal.ts:7:5 
    Property 'toUrl' of type '(rel: string) => Url' is not assignable to string index type 'Link'.
[default] C:\Users\xeno\IdeaProjects\rpf-ui\src\util\Hal.ts:16:5 
    Property 'toUrl' of type '(rel: string) => Url' is not assignable to string index type 'Link'.

这是实例化代码,它可以工作(没有toUrl代码)

    client.fetch( '' ).then( response => {
        return response.json();
    } ).then( json => {
        let hal: HalJson = Object.assign( new HalJson(), json );
        hal._links = Object.assign( new HalLinks(), hal._links );
        log.debug( "json", hal );

我正试图找出一种方法可以从Url有效负载中获取application/hal+json对象

(或者,如果有人知道任何打字机定义库会采用hal json链接并使其严格打字,请在评论中随意提及)

1 个答案:

答案 0 :(得分:0)

编译器抱怨,因为Links的实例可以像这样使用:

let a = links["toUrl"]("rel");

那么a的类型是什么?是Link还是Url
你可以这样做:

interface Links {
    [text: string]: Link | Url;
    toUrl(rel: string): Url;
}

class HalLinks implements Links {
    toUrl(rel: string): Url {
        let link = <Link> this[rel];
        return parse(link.href);
    }
    [text: string]: Link | Url;
}

但是,您需要投射从HalLinks检索到的所有内容:

let a1 = links["rel"] as Link;
let a2 = links["rel"] as Url; // no error, which isn't good.

我建议需要更多代码,但我认为使用起来会更容易:

interface Links {
    [text: string]: Link;
}

class HalLink {
    constructor(private link: Link) {}

    get href(): string {
        return this.link.href;
    }

    get url(): Url {
        return parse(this.link.href);
    }
}

class HalLinks {
    private links: { [rel: string]: HalLink };

    constructor(links: Links) {
        this.links = {};

        for (let key in links) {
            this.links[key] = new HalLink(links[key]);
        }
    }

    get(rel: string): HalLink {
        return this.links[rel];
    }

    url(rel: string): Url {
        return this.links[rel].url;
    }
}

let links: HalLinks;

let link1 = links.get("rel1");
let href1 = link1.href;
let url1 = link1.url;

let url2 = links.url("rel2");