1

I would like to check whether provided value match defined regex-match string type. Based on that I would return proper value. I need that to properly override my method.

EXAMPLE

type RegexType =`${string}/:${string}`

function myFunction(url: string): string;
function myFunction<P extends RegexType>(
  url: P,
): number;
function myFunction<P extends string>(value: P) {
  // value is typeof RegexType if yes then reutrn numberFunction otherwise stringFunction
}


const numberFunction = (): number => 1;
const stringFunction = (): string => '1';

PLAYGROUND

I know that I can use regex inside of the function, but then I meet another problem, that type is not properly interfered for template string

type RegexType =`${string}/:${string}`

function myFunction<P extends RegexType>(
  url: P,
): number;
function myFunction(url: string): string;
function myFunction<P extends string>(value: P) {
  // value is typeof RegexType if yes then reutrn numberFunction otherwise stringFunction
  return value.match('\/:') ? numberFunction() : stringFunction();
}


const numberFunction = (): number => 1;
const stringFunction = (): string => '1';
const testValue = '123/:123';

// ERROR
const valueNum: number = myFunction(`${testValue}`);
// VALID
const valueNum123: number = myFunction('123/:123');

PLAYGROUND

1 Answer 1

1

This should do what you want. Unfortunately it requires an any in the return statement, but the return type of the function causes an error as you wanted:

type RegexType =`${string}/:${string}`

function myFunction<P extends string>(value: P): P extends RegexType ? number : string {
  return value.match('\/:') ? numberFunction() : stringFunction() as any;
}

const numberFunction = (): number => 1;
const stringFunction = (): string => '1';
const testValue = '123/:123';

// ERROR
const valueNum: number = myFunction(`${testValue}`);
// VALID
const valueNum123: number = myFunction('123/:123');

Unfortunately, doing this can easily make way for potential type errors by making incorrect assumptions when you're not able to determine the type of a string, for example the following is considered correct in typescript, but will result in the error "valueNum.substr is not a function":

const testValue = '123/:123';
const valueNum: string = myFunction(`${testValue}`);
valueNum.substr(1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.