Skip to content

Instantly share code, notes, and snippets.

@jumpinjackie
Last active September 28, 2018 13:41
Show Gist options
  • Save jumpinjackie/82b6c794e3abc4bcf64d83bdbb387c23 to your computer and use it in GitHub Desktop.
Save jumpinjackie/82b6c794e3abc4bcf64d83bdbb387c23 to your computer and use it in GitHub Desktop.
Immutable.JS TypeScript 2.8 edition
//Some example interface
interface IGeographicCoordinate {
lat: number;
lng: number;
}
interface IPlacemark {
id: number;
coordinate: IGeographicCoordinate;
name: string;
}
interface ISearchResult {
query: string;
results: IPlacemark[];
}
// ============= The magic sauce ============== //
interface ImmutableObject<T> {
get<P extends keyof T>(key: P): T[P] extends Array<infer U> ? ImmutableList<U> : T[P] extends object ? ImmutableObject<T[P]> : T[P];
}
interface ImmutableList<T> {
count(): number;
get(index: number): T extends object ? ImmutableObject<T> : T;
}
// The fromJS() API from immutable.js
declare function fromJS<T>(obj: T): ImmutableObject<T>;
// ============= End magic sauce =============== //
function test() {
const pm1: IPlacemark = {
id: 1,
coordinate: {
lat: 0,
lng: 0
},
name: "Null Island"
};
const pm2: IPlacemark = {
id: 2,
coordinate: {
lat: -37.815080,
lng: 144.963886
},
name: "Melbourne"
};
const results: ISearchResult = {
query: "Some example placemarks",
results: [
pm1,
pm2
]
}
const imp1 = fromJS(pm1); //ImmutableObject<IPlacemark>
const imp2 = fromJS(pm2); //ImmutableObject<IPlacemark>
const iResults = fromJS(results); //ImmutableObject<ISearchResults>
const a = imp1.get("id"); //number
const b = imp1.get("coordinate"); //ImmutableObject<IGeographicCoordinate>
const blat = b.get("lat"); //number
const blng = b.get("lng"); //number
const c = imp1.get("name"); //string
const d = iResults.get("query"); //string
const e = iResults.get("results"); //ImmutableList<IPlacemark>
const f = e.get(0); //ImmutableObject<IPlacemark>
const g = e.get(1); //ImmutableObject<IPlacemark>
const h = f.get("coordinate"); //ImmutableObject<IGeographicCordinate>
const i = g.get("coordinate"); //ImmutableObject<IGeographicCordinate>
const hlat = h.get("lat"); //number
const hlng = h.get("lng"); //number
const ilat = i.get("lat"); //number
const ilng = i.get("lng"); //number
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment