【问题标题】:Creating an alias for a function type为函数类型创建别名
【发布时间】: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&lt;(input: string) =&gt; string&gt;('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


【解决方案1】:

TypeScript 确实有type aliases!正如您所怀疑的,您没有将其声明为interface。相反,您只需将其声明为type,使用与您使用的基本相同的语法(使用= 赋值):

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

如果您有时间,我建议您通读一下TypeScript Handbook,因为它包含您在使用 TypeScript 编程时可能会发现有用的其他好东西。希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 2021-03-03
    • 2020-02-04
    相关资源
    最近更新 更多