为函数类型创建别名

时间:2017-07-20 18:54:12

标签: angularjs typescript type-alias

在我正在处理的应用程序中,我不得不将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中创建函数类型的别名吗?

1 个答案:

答案 0 :(得分:1)

TypeScript确实有type aliases!正如您所怀疑的那样,您不会将其声明为interface。相反,您只需要将其声明为type,使用与您使用的语法基本相同的语句(使用=进行分配):

export type IFilterFunctionType = (input: string) => string;  
return $filter<IFilterFunctionType>('tel')('1234567890');

如果您有时间,我建议您仔细阅读TypeScript Handbook,因为它包含您在使用TypeScript编程时可能会觉得有用的其他好东西。希望有所帮助。

相关问题