Skip to content

Instantly share code, notes, and snippets.


Daan Scheerens dscheerens

View GitHub Profile
dscheerens / ng-init.decorator.ts
Created Oct 21, 2020
Initializer decorator for Angular components (fully type-safe!)
View ng-init.decorator.ts
import { Subscription } from 'rxjs';
const GLOBAL_COMPONENT_SUBSCRIPTIONS = new WeakMap<any, Set<Subscription>>();
export function NgInit<
TargetType extends { constructor: Function, ngOnInit?(): void, ngOnDestroy?(): void },
PropertyKey extends string,
PropertyContainer extends { [k in PropertyKey]: () => (void | Subscription) },
FunctionType extends PropertyContainer[PropertyKey]
dscheerens / memoize.decorator.ts
Created Oct 7, 2020
TypeScript memoize decorator for get accessor functions
View memoize.decorator.ts
const GLOBAL_MEMOIZATION_MAP = new WeakMap<any, Map<string, any>>();
export function memoize<T extends { constructor: Function }>(target: T, propertyKey: string, descriptor: PropertyDescriptor) {
const originalGet = descriptor.get;
if (!originalGet) {
throw new Error(`Cannot apply @memoize decorator to '${}.${propertyKey}' since it has no get accessor`);
descriptor.get = function(this: any): any {
dscheerens / define-translation-keys.ts
Created May 6, 2020
Utility function to define type safe translation keys
View define-translation-keys.ts
type TranslationKeyPlaceholder = typeof TRANSLATION_KEY_PLACEHOLDER;
export interface TranslationStructure {
[key: string]: TranslationStructure | TranslationKeyPlaceholder;
export type TranslationKeysOf<T extends TranslationStructure> = {
[P in keyof T]: T[P] extends TranslationStructure ? TranslationKeysOf<T[P]> : string
dscheerens / injection-token-factory-builder.ts
Created Aug 15, 2019
Builder pattern applied to InjectionToken factory functions
View injection-token-factory-builder.ts
// ========================================
// app-module.ts
// ========================================
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NumbersModule } from './numbers';
dscheerens / observe-property.ts
Last active Sep 30, 2019
Property observe function
View observe-property.ts
import { BehaviorSubject, Observable } from 'rxjs';
* Observes the specified property and returns a stream that emits all values which are assigned to the property. When subscribing to the
* resulting stream it will always first emit the current value of the property, followed by all new values that are assigned to it.
* @param target Object containing the property.
* @param key Key of the property that is to be observed.
* @returns A stream of all values that are assigned to the specified property, starting with the current value of the property.
You can’t perform that action at this time.