Created
September 23, 2021 13:14
-
-
Save bhubr/49340762a961012b5c72dfc44519e9d5 to your computer and use it in GitHub Desktop.
TypeScript type guards
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
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) | |
} | |
} |
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
// 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