Skip to content

Instantly share code, notes, and snippets.

@shepherdjerred
Created May 5, 2024 02:45
Show Gist options
  • Save shepherdjerred/0976bc9d86f0a19a75757bd69062e292 to your computer and use it in GitHub Desktop.
Save shepherdjerred/0976bc9d86f0a19a75757bd69062e292 to your computer and use it in GitHub Desktop.
type PlayingState = {
song: string;
position: number; // how many seconds into the song we're in
duration: number; // how many seconds long the song is
}
type StoppedState = {}
type State = PlayingState | StoppedState
// take the state and seek to a particular position
function seek(state: PlayingState, position: number): PlayingState {
// note that we cannot get rid of this runtime in every case, but it will now be a compile time error if we try to seek if a song is not playing
if (position > state.duration) {
throw Error
}
return {
...state,
position
}
}
// initial state
let state: State = {
song: "Hooked on a Feeling",
duration: 90,
position: 0,
}
// seek to some part of the song
state = seek(state, 10)
// stop the current song
let state = {}
// this will not compile
seek(state, 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment