Last active
May 21, 2019 11:03
-
-
Save Maistho/12fc98592cf841a949ee259ee3a6eeae to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Data { | |
| a?: string | |
| b?: number | |
| static fromJson(json: Record<string, any>): Data { | |
| return {a: json.a, b: json.b} | |
| } | |
| } | |
| class UIProperty { | |
| key: keyof Data | |
| label: string | |
| value?: string | number | |
| // It's possible to simplify the types of this constructor somewhat, but the dart way is actually quite a lot better than typescript imo | |
| constructor({key, label, value}: {key: keyof Data, label: string, value?: string | number}) { | |
| this.key = key | |
| this.label = label | |
| this.value = value | |
| } | |
| } | |
| async function getData() { | |
| return Data.fromJson({a: 'a', b: 2}) | |
| } | |
| function createPropertyList() { | |
| // Typescript will correctly infer the type of list to be UIProperty[] | |
| let list = [ | |
| // Typescript will also understand that key: 'a' is a key of Data and that this is type-safe | |
| new UIProperty({ key: 'a', label: 'Label A' }), | |
| new UIProperty({ key: 'b', label: 'Label B' }), | |
| // This would however not compile, since 'c' is not a keyof Data | |
| new UIProperty({ key: 'c', label: 'Label C' }), | |
| ] | |
| getData().then(data => { | |
| for (let prop of list) { | |
| // This is also typesafe, since prop.key is a key of data | |
| prop.value = data[prop.key] | |
| } | |
| }) | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment