Skip to content

Instantly share code, notes, and snippets.

@chrismatheson
Created July 4, 2018 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismatheson/07d7edc66867b2cc157e485c72626a34 to your computer and use it in GitHub Desktop.
Save chrismatheson/07d7edc66867b2cc157e485c72626a34 to your computer and use it in GitHub Desktop.
Fully typecheked JS with TS lib thing
/** "TypeDef" lib */
function Obj<T>(a: T): T {
return undefined;
}
function Str(): string {
return undefined;
}
function Optional<T>(a: T) {
return undefined as (T | undefined);
}
function Throwing<T>(a: T):T {
if (a === void 0) {
throw new Error('Type check error');
}
return undefined;
}
function Logging<T>(a: T):T {
if (a === void 0) {
console.error('Type check error');
}
return undefined;
}
/** =============== */
function meh(opts = Optional("hello")) {
}
function foo(x = Throwing("")) {
}
const SharedType = Obj({ message: Str() })
function Greeter(greeting = SharedType) {
this.greeting = greeting;
}
Greeter.prototype.greet = function() {
return "Hello, " + this.greeting;
}
// Oops, we're passing an object when we want a string. This will print
// "Hello, [object Object]" instead of "Hello, world" without error.
let greeter = new Greeter({message: "world"});
let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
alert(greeter.greet());
};
document.body.appendChild(button);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment