验证Typescript中regex匹配字符串类型的类型



我想检查提供的值是否与定义的正则表达式匹配字符串类型。基于此,我将返回适当的值。我需要它来正确地覆盖我的方法。

示例

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';

游乐场

我知道我可以在函数中使用regex,但后来我遇到了另一个问题,即模板字符串的类型没有受到适当的干扰

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');

游乐场

这应该是您想要的。不幸的是,它在return语句中需要一个any,但函数的返回类型会导致您想要的错误:

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');

不幸的是,这样做很容易为潜在的类型错误让路,因为当你无法确定字符串的类型时,会做出不正确的假设,例如以下在typescript中被认为是正确的,但会导致错误";valueNum.substr不是一个函数":

const testValue = '123/:123';
const valueNum: string = myFunction(`${testValue}`);
valueNum.substr(1)

相关内容

最新更新