Created
August 17, 2017 20:05
-
-
Save jonnyreeves/fa89cf880441eb023598c5296c8bf342 to your computer and use it in GitHub Desktop.
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 function fromObject<T extends jspb.Message, U>(c: new () => T, obj: U): T { | |
const instance = new c(); | |
Object.keys(obj) | |
.forEach(key => { | |
const setterName = makeSetterFuncName(key); | |
(instance as any)[setterName] = (obj as any)[key]; | |
}); | |
return instance; | |
} | |
function makeSetterFuncName(key: string): string { | |
switch (key) { | |
case "pb_abstract": | |
case "pb_boolean": | |
case "pb_break": | |
case "pb_byte": | |
case "pb_case": | |
case "pb_catch": | |
case "pb_char": | |
case "pb_class": | |
case "pb_const": | |
case "pb_continue": | |
case "pb_debugger": | |
case "pb_default": | |
case "pb_delete": | |
case "pb_do": | |
case "pb_double": | |
case "pb_else": | |
case "pb_enum": | |
case "pb_export": | |
case "pb_extends": | |
case "pb_false": | |
case "pb_final": | |
case "pb_finally": | |
case "pb_float": | |
case "pb_for": | |
case "pb_function": | |
case "pb_goto": | |
case "pb_if": | |
case "pb_implements": | |
case "pb_import": | |
case "pb_in": | |
case "pb_instanceof": | |
case "pb_int": | |
case "pb_interface": | |
case "pb_long": | |
case "pb_native": | |
case "pb_new": | |
case "pb_null": | |
case "pb_package": | |
case "pb_private": | |
case "pb_protected": | |
case "pb_public": | |
case "pb_return": | |
case "pb_short": | |
case "pb_static": | |
case "pb_super": | |
case "pb_switch": | |
case "pb_synchronized": | |
case "pb_this": | |
case "pb_throw": | |
case "pb_throws": | |
case "pb_transient": | |
case "pb_try": | |
case "pb_typeof": | |
case "pb_var": | |
case "pb_void": | |
case "pb_volatile": | |
case "pb_while": | |
case "pb_with": | |
key = key.substr(3); | |
break; | |
} | |
const upperKey = key.charAt(0).toUpperCase() + key.substr(1); | |
return `set${upperKey}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@MarcusLongmuir WDYT? Usage is a little clunky as you need to provide both generic types (although my TS is weak, can you express this better?)