Skip to content

Instantly share code, notes, and snippets.

@kamataryo
Created October 4, 2019 07:15
Show Gist options
  • Save kamataryo/011e4c142a90ac0324e74d303f87fee9 to your computer and use it in GitHub Desktop.
Save kamataryo/011e4c142a90ac0324e74d303f87fee9 to your computer and use it in GitHub Desktop.
TypeScript TypeGuard example with side effects
type Ref = { message?: string; isValid?: boolean };
const isValid = (value: any, ref: Ref): value is string => {
if (typeof value === "string") {
if (value.length > 10) {
ref.isValid = false;
ref.message = "Value should have length less than 10.";
} else {
ref.isValid = true;
ref.message = "OK";
}
} else {
ref.isValid = false;
ref.message = "Value should be string.";
}
return ref.isValid;
};
const main = (value: any) => {
const ref: Ref = {};
if (isValid(value, ref)) {
value; // type string
console.log(ref.message);
} else {
value; // type any
console.log(ref.message);
}
};
main("hello!!!!!!!!!!!!!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment