Closed HudsonAfonso closed 7 months ago
Ooooh, this has a really nice example of how patterns make validating JSON super compact and readable. Gonna translate it back to plain JS and store it here, so I can grab it later when we merge the new-README branch.
Destructuring, no checks:
var json = {
'user': ['Lily', 13]
};
var {user: [name, age]} = json;
Destructuring with checks that everything is correct and of the expected shape:
if ( json.user !== undefined ) {
var user = json.user;
if (Array.isArray(user) &&
user.length == 2 &&
typeof user[0] == "string" &&
typeof user[1] == "number") {
var name = user[0];
var age = user[1];
print(`User ${name} is ${age} years old.`);
}
}
Same checks, but in pattern-matching:
if( json is {user: [String and let name, Number and let age]} ) {
print(`User ${name} is ${age} years old.`);
}
https://dart.dev/language/patterns