Skip to content

Instantly share code, notes, and snippets.

@geon
Created December 8, 2016 12:13
Show Gist options
  • Save geon/04944c01b8d0255f3cc83eb16d66b15e to your computer and use it in GitHub Desktop.
Save geon/04944c01b8d0255f3cc83eb16d66b15e to your computer and use it in GitHub Desktop.
Typed Backbone-style models with `keyof` in Typescript 2.1
class Model<T> {
props: T;
constructor(initial: T | void){
if (initial) {
this.props = initial;
}
}
set<K extends keyof T>(propName: K, value: T[K]) {
this.props[propName] = value;
}
get(propName: keyof T) {
return this.props[propName];
}
}
class User extends Model<{
id?: number,
fullName?: string,
email?: string
}> {};
const user = new User({
fullName: 'Victor Widell'
});
user.set('id', 1337);
console.log(user.get('id'), user.get('fullName'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment