【发布时间】:2017-07-20 18:54:12
【问题描述】:
在我正在开发的应用程序中,我必须将 AngularJS 过滤器和指令转换为 TypeScript v2.4。
我发现了一种模式,我必须做的就是让指令与 AngularJS 的 $filter 服务一起工作 - 我需要使用 $filter<\T>('???')(value) 重载,以便将自定义电话格式过滤器应用于指令。
这是翻译后指令的链接函数:
link: (scope: any, elem: any, attrs: any, ctrl: angular.INgModelController) => {
const mask: string = '(999) 999-9999';
$(elem).mask(mask);
const nonDigitCharacers: RegExp = /[^0-9]/g;
elem.on('keydown', (evt: any) => {
scope.$evalAsync(elem.triggerHandler.bind(elem, 'change', evt));
});
ctrl.$validators.minLength = (modelValue: string, viewValue: string) => {
let minLength: number = 0;
if (attrs.minlength)
minLength = parseInt(attrs.minlength);
let stringValue: string = $filter<(input: string) => string>('tel')(modelValue);
let longEnough: boolean = stringValue.length > minLength;
// If value not required, and nothing is entered, the value is valid.
if (!attrs.required && stringValue.length === 0)
return true;
// If value is required, and nothing is entered, this value is 'valid'.
// The point of this code is to not interfere with a required attribute!
if (attrs.required && stringValue.length === 0)
return true;
return longEnough;
};
ctrl.$parsers.unshift((viewValue: string) => {
let digitsOnly: string = viewValue.replace(nonDigitCharacers, '');
return digitsOnly;
});
ctrl.$formatters.push((value: string) => {
return $filter<(input: string) => string>('tel')(value);
});
}
...我注意到的是我必须在此执行两次$filter<(input: string) => string>('tel')(value),否则它不会编译为 JavaScript。然而,这似乎很浪费——我想做的是创建 C# 开发人员可能识别为委托名称的名称,或者其他语言可能称为类型别名的名称,如下所示:
// It wouldn't be an interface, but I don't really know what it *would* be...
export interface IFilterFunctionType = (input: string) => string;
// Using it...
return $filter<IFilterFunctionType>('tel')('1234567890');
问题:如果有的话,我可以通过什么方式在 TypeScript 2.4 中创建函数类型的别名?
【问题讨论】:
-
你不知道 TypeScript 中的 type aliases 吗?
-
我不是。但是,如果您能找到更好的方式来表达该响应,我会将其作为答案。如果不是很明显的话,我对 TypeScript 有很多不了解的地方。
-
当然,刚刚做到了。干杯。
标签: angularjs typescript type-alias