-
-
Save alekpopovic/77669320de138799c5cab8ad3461d861 to your computer and use it in GitHub Desktop.
Typescript example DSL
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
interface MyProgramDSL<T> { | |
read: () => Promise<string>; | |
write: (value: string) => Promise<void> | |
done: (value: T) => Promise<T> | |
} | |
const MyProgram = async ({ read, write, done }: MyProgramDSL<string>) => { | |
await write("Hello, what is your name?"); | |
const name = await read(); | |
return done(`Your name: ${name}, has ${name.length} letters.`); | |
} | |
const promptAlertInterpreter = <T>() => ({ | |
read: async () => prompt(), | |
write: async (value: string) => alert(value), | |
done: async (value: T) => value | |
}); | |
class PlatformConsoleInterpreter<T> implements MyProgramDSL<T> { | |
async read() { return navigator.platform } | |
async write(value) { console.log(value) } | |
async done(value) { return value } | |
} | |
MyProgram(promptAlertInterpreter<string>()).then(alert); | |
MyProgram(new PlatformConsoleInterpreter).then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment