Created
October 4, 2019 07:15
-
-
Save kamataryo/011e4c142a90ac0324e74d303f87fee9 to your computer and use it in GitHub Desktop.
TypeScript TypeGuard example with side effects
This file contains 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
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