typescript - Checking validity of string literal union type at runtime? -
i have simple union type of string literals , need check it's validity because of ffi calls "normal" javascript. there way ensure variable instance of of literal strings at runtime? along lines of
type mystrings = "a" | "b" | "c"; mystrings.isassignable("a"); // true mystrings.isassignable("d"); // false 
since typescript 2.1, can other way around with keyof operator. 
the idea follows. since string literal type information isn't available in runtime, define plain object keys strings literals, , make type of keys of object.
as follows:
// values of dictionary irrelevant const mystrings = {   a: "",   b: "" }  type mystrings = keyof typeof mystrings;  ismystrings(x: string): x mystrings {   mystrings.hasownproperty(x); }  const a: string = "a"; if(ismystrings(a)){   // ... use if typed mystring assignment within block: typescript compiler trusts our duck typing! } 
Comments
Post a Comment