Created
March 2, 2017 15:26
-
-
Save JohannesRudolph/55160d2503b2369444a529429ff8a746 to your computer and use it in GitHub Desktop.
HAL Models with TypeScript 2.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type HalUrl = string; | |
export interface HalLink { | |
href: HalUrl; | |
} | |
export interface HalObjectLinks { | |
self: HalLink; | |
} | |
export interface HalObject<T extends HalObjectLinks> { | |
'_links': T; | |
[key: string]: any; // other properties of the object | |
} | |
export class Hal { | |
public static findHref<T extends HalObjectLinks, K extends keyof T>(object: HalObject<T>, rel: K): string { | |
const link = object._links ? object._links[<string>rel] : null; | |
if (!link) { | |
throw new Error('HAL object did not have link: ' + rel); | |
} | |
return link.href; | |
} | |
} | |
export interface CustomerLinks extends HalObjectLinks { | |
addresses: HalLink; | |
} | |
export interface Customer extends HalObject<CustomerLinks> { | |
name: string; | |
} | |
const customer: Customer = <any>null; | |
Hal.findHref(customer, 'addresses'); | |
// error: 'Argument of type '"users"' is not assignable to parameter of type '"self" | "addresses"'.' | |
Hal.findHref(customer, 'users'); | |
Hal.findHref(customer, 'self'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment