Skip to content

Instantly share code, notes, and snippets.

@bhubr
Created September 23, 2021 13:14
Show Gist options
  • Save bhubr/49340762a961012b5c72dfc44519e9d5 to your computer and use it in GitHub Desktop.
Save bhubr/49340762a961012b5c72dfc44519e9d5 to your computer and use it in GitHub Desktop.
TypeScript type guards
class NetworkError extends Error {}
class OtherError extends Error {}
function flipCoin() {
return Math.random() > 0.7;
}
function networkRequest() {
if (flipCoin()) {
throw new NetworkError('Network error ...');
}
return 'Network OK';
}
function otherFunction() {
if (flipCoin()) {
throw new OtherError('Other error ...');
}
return 'Other OK';
}
try {
const networkResult = networkRequest();
console.log('network result ->', networkResult);
const otherResult = otherFunction();
console.log('other result ->', otherResult);
throw new Error('this is another error');
} catch(err) {
if (err instanceof NetworkError) {
console.log('Error is a NetworkError -> ', err);
} else if (err instanceof OtherError) {
console.log('Error is a OtherError -> ', err);
} else {
console.log('Error is something else ->', err)
}
}
// padLeft(3, 'x') => ' x'
// padLeft('.', 'x') => '.x'
function padLeft(padding: number | string, input: string): string {
if (typeof padding === 'number') {
return new Array(padding + 1).join(" ") + input;
}
return padding + input;
}
console.log(padLeft(10, 'x'));
console.log(padLeft('...', 'y'));
// console.log(padLeft({}, 'x'));
// console.log('test' + 5)
// console.log(new Array(5));
// console.log(new Array('toto'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment