Skip to content

Instantly share code, notes, and snippets.

@JohannesRudolph
Created March 2, 2017 15:26
Show Gist options
  • Save JohannesRudolph/55160d2503b2369444a529429ff8a746 to your computer and use it in GitHub Desktop.
Save JohannesRudolph/55160d2503b2369444a529429ff8a746 to your computer and use it in GitHub Desktop.
HAL Models with TypeScript 2.1
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