Skip to content

Instantly share code, notes, and snippets.

@Cogentx
Created March 25, 2022 17:47
Show Gist options
  • Save Cogentx/63c1bb6989c3e7c5b2a75a4d2ccd7d86 to your computer and use it in GitHub Desktop.
Save Cogentx/63c1bb6989c3e7c5b2a75a4d2ccd7d86 to your computer and use it in GitHub Desktop.
TypeScript Temporal Uncertainty
let displayNames = ['Joe Doe', 'Jane Doe'];
const getSuffix = () => {
if (Math.random() * 100 < 50) {
return null;
}
return 'md';
};
displayNames.forEach((name) => {
let suffix = getSuffix();
/*The challenge is that TypeScript allows for both Async and Sync execution. Since TypeScript often errs on the side of Type-Safety and in the case of Async has no guarantee of what a value will be at execution, you can get a Type Error that you know is not correct (code below-showing error even after a NULL check). A solution is to save the value to a local variable. This assures TypeScript of Type at execution and there is no longer a Type Error given.*/
if (suffix != null) {
const suffixLocal = suffix; // prevents Type Error
setTimeout(() => {
name += ', ' + suffixLocal.toUpperCase();
console.log({ name });
},100);
}
suffix = null;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment