为函数类型创建别名

问题描述:

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

+0

您是否知道TypeScript中的[type aliases](https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases)? – jcalz

+0

我没有。如果你能找到一个更好的方式来表达这种回应,那么我会把它当作答案。有很多我不知道TypeScript的,如果这不明显。 –

+0

当然,只是。干杯。 – jcalz

TypeScript确实有type aliases!如您所怀疑的,您不会将其声明为interface。相反,你只需要把它声明为一个type,基本上使用您使用相同的语法(分配与=):

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

我建议您采取TypeScript Handbook的通读,如果你有时间,因为它包含在TypeScript中编程时可能会用到的其他好东西。希望有所帮助。