Created
January 30, 2019 05:26
-
-
Save kestred/b2ac2bc05cd35eaa3e083cc83446d9cf 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
import { | |
Boolean, | |
Number, | |
String, | |
Literal, | |
Array, | |
Tuple, | |
Record, | |
Union, | |
Null, | |
Partial, | |
Static, | |
} from "runtypes"; | |
const Vector = Tuple(Number, Number, Number); | |
const Planet = Record({ | |
type: Literal('planet'), | |
location: Vector, | |
mass: Number, | |
population: Number, | |
habitable: Boolean, | |
}); | |
const Rank = Union( | |
Literal('captain'), | |
Literal('first mate'), | |
Literal('officer'), | |
Literal('ensign'), | |
); | |
const CrewMember = Record({ | |
name: String, | |
age: Number, | |
rank: Rank, | |
home: Planet, | |
}); | |
const Ship = Record({ | |
type: Literal('ship'), | |
location: Vector, | |
mass: Number, | |
name: String, | |
crew: Array(CrewMember), | |
}); | |
const RegisteredShip = Ship.And(Record({ | |
// All registered ships must have this flag | |
isRegistered: Literal(true), | |
})).And(Partial({ | |
// We may or may not know the ship's classification | |
shipClass: Union(Literal('military'), Literal('civilian')), | |
// We may not know the ship's rank (may be undefined as part of a "Partial"), | |
// we may also know that a civilian ship doesn't have a rank (null) | |
rank: Rank.Or(Null), | |
})); | |
const MilitaryShip = Ship.And(Record({ | |
shipClass: Literal('military'), | |
lastDeployedTimestamp: Number.Or(Null), | |
})); | |
var ussSpacejam: Static<typeof RegisteredShip> = { | |
type: "ship", | |
location: [0.5, 0.5, 0.5], | |
mass: 2_000_000, | |
name: "USS Spacejam", | |
crew: [], | |
isRegistered: true, | |
// e.g. this works | |
rank: undefined | |
}; | |
console.warn('isRegistered', RegisteredShip.guard(ussSpacejam)); // true | |
console.warn('isMilitary', MilitaryShip.guard(ussSpacejam)); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment