Last active
January 6, 2021 23:16
-
-
Save aboglioli/17028f71497b385fba4c4eefc1f18263 to your computer and use it in GitHub Desktop.
Typescript class deserialization (using JSON.parse() and public properties)
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
const json = `{ | |
"type": "two", | |
"value": 25.5, | |
"items": [{ | |
"order": 2, | |
"value": "hello" | |
}, { | |
"order": 5, | |
"value": "bye" | |
}] | |
}`; | |
enum Type { | |
One = 'one', | |
Two = 'two', | |
Three = 'three', | |
} | |
class Item { | |
constructor( | |
public order: number, | |
public value: string, | |
) { } | |
} | |
class Data { | |
constructor( | |
public type: Type, | |
public value: number, | |
public items: Item[], | |
) { } | |
public doSomething(): void { | |
console.log('Doing...', this.type, this.value, this.items.length); | |
} | |
} | |
function main() { | |
const data: Data = JSON.parse(json); | |
console.log(data); | |
data.doSomething(); // ERROR: not really an instance | |
console.assert(data.type === Type.Two); | |
console.assert(data.value === 25.5); | |
console.assert(data.items.length === 2); | |
console.assert(data.items[0].order === 2); | |
console.assert(data.items[0].value === 'hello'); | |
console.assert(data.items[1].order === 5); | |
console.assert(data.items[1].value === 'bye'); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment