So I have a string union type
type S = 'a' | 'b' | 'c';
I want to initialize a value of type S, while asserting that is of type S. With a variable, it's very easy:
const s1: S = 'a';
const s2: S = 'z'; // error
However, I just want to instantiate the value itself, along the lines of 'a' as S
but checking that 'a'
is of type S
.
The exact use case is that I'm using a library that provides a function f(s: string)
, but I want to ensure that when I call it, I only call it with the strings I deem ok. Since [afaik] you can't narrow the signature from outside the library, I was thinking of doing something like f('a' as S)
every time I used f
.
Defining my own function g = (s: S) => f(s)
isn't a great option because actually f
's signature looks like f(s: string, t: T)
where T
is a complex, library defined type that I'm not sure is even exported.
What would be the best way to accomplish this?