Typescript 函数参数类型返回特定值
目前,我正在传入一个回调,以将原始值解析为特定的泛型类型Typescript 函数参数类型返回特定值,typescript,Typescript,目前,我正在传入一个回调,以将原始值解析为特定的泛型类型 protected constructValue<TResult>(key: string, parser: Function): TResult { const rawValue: string = /* assign raw value here */; return parser(rawValue); } protectedconstructValue(键:字符串,解析器:函数):TResult{ c
protected constructValue<TResult>(key: string, parser: Function): TResult {
const rawValue: string = /* assign raw value here */;
return parser(rawValue);
}
protectedconstructValue(键:字符串,解析器:函数):TResult{
const rawValue:string=/*在此处指定原始值*/;
返回解析器(rawValue);
}
有没有办法确保解析器函数必须是返回泛型类型值的回调?所以这是可行的
constructValue('myKey',Number)
但这不会
constructValue('myKey',value=>value=='true')
因为解析器返回的是布尔值而不是数字。您可以将解析器的类型从泛型
函数
限制为:
parser: (...args: any) => TResult
或者更好地定义arg是什么:
parser: (rawValue: string) => TResult