I am trying to check some property of a variable with a regular Expression and if that matched, I want the type of that variable be inferred to a more specific type.
I have an example in the typescript playground:
type xN = `x${number}`;
const reg = new RegExp("x([0-9]+)");
function check(s:string):RegExpMatchArray | null /* asserts s is xN*/{
return s.match(reg);
}
declare const test :string;
const match = check(test);
if(match){
// test should be of type xN now
match.groups // use that non-null match variable, too...
}
Is there a way to do that with one function in (TS 4.5.4)? If not, how would you do it neatly?