Created
December 5, 2020 21:16
-
-
Save steverhall/228fc32f143b53933548dd81021192b5 to your computer and use it in GitHub Desktop.
Getting/Setting Typescript class properties dynamically
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
class Passport { | |
ecl: string = ''; | |
pid: string = ''; | |
eyr: string = ''; | |
hcl: string = ''; | |
byr: string = ''; | |
hgt: string = ''; | |
iyr: string = ''; | |
cid: string = ''; | |
} | |
function getProperty<T, K extends keyof T>(obj: T, key: K) { | |
return obj[key]; | |
} | |
function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]) { | |
obj[key] = value; | |
} | |
//Instead of using passport.byr = 'myvalue', we'll set using a dynamic property | |
var passport = new Passport(); | |
var dynProp = 'byr'; | |
setProperty(passport, dynProp as keyof Passport, 'myvalue'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment