具有相同参数的 TypeScript 多个返回类型

标签 typescript angular2-forms typescript2.0

背景

为了融入 TypeScript 的精神,我在我的组件和服务中编写了完全类型化的签名,它扩展到我的 angular2 表单的自定义验证函数。

我知道I can overload a function signature , 但这要求每个返回类型的参数都不同,因为 tsc将每个签名编译为一个单独的函数:

function pickCard(x: {suit: string; card: number; }[]): number;
function pickCard(x: number): {suit: string; card: number; };
function pickCard(x): any { /*common logic*/ };

我也知道我可以返回一个类型(如 Promise),它本身可以是多个子类型:

private active(): Promise<void|null> { ... }

但是,在 angular2 自定义表单验证器的上下文中,单个签名(一个类型为 FormControl 的参数)可以返回两种不同的类型:一个 Object有表格错误,或 null表示控件没有错误。

这显然行不通:

private lowercaseValidator(c: FormControl): null;
private lowercaseValidator(c: FormControl): Object {
    return /[a-z]/g.test(c.value) ? null : { lowercase: this.validationMessages.lowercase };
}

也不行

private lowercaseValidator(c: FormControl): null|Object {...}
private lowercaseValidator(c: FormControl): <null|Object> {...}

(有趣的是,我得到了以下错误,而不是更多信息:

error TS1110: Type expected.
error TS1005: ':' expected.
error TS1005: ',' expected.
error TS1128: Declaration or statement expected.

)

长话短说

我只是简单地使用

private lowercaseValidator(c: FormControl): any { ... }

这似乎否定了类型签名的优势?

更笼统一点,期待ES6

虽然这个问题的灵感来自 angular2 表单验证器,它由框架直接处理,因此您可能不关心声明返回类型,但它仍然普遍适用,特别是考虑到像 function (a, b, ...others) {} 这样的 ES6 结构。

也许避免编写可以返回多种类型的函数是更好的做法,但由于 JavaScript 的动态特性,它是相当惯用的。

引用资料

最佳答案

好的,如果你想要正确的类型,这是正确的方法:

type CustomType = { lowercase: TypeOfTheProperty };
// Sorry I cannot deduce type of this.validationMessages.lowercase,
// I would have to see the whole class. I guess it's something
// like Array<string> or string, but I'm not Angular guy, just guessing.

private lowercaseValidator(c: FormControl): CustomType | null {
    return /[a-z]/g.test(c.value) ? null : { lowercase: this.validationMessages.lowercase };
}

更一般的例子

type CustomType = { lowercase: Array<string> };

class A {
      private obj: Array<string>;

      constructor() {
            this.obj = Array<string>();
            this.obj.push("apple");
            this.obj.push("bread");
      }

      public testMethod(b: boolean): CustomType | null {
            return b ? null : { lowercase: this.obj };
      }
}

let a = new A();
let customObj: CustomType | null = a.testMethod(false);
// If you're using strictNullChecks, you must write both CustomType and null
// If you're not CustomType is sufficiant

关于具有相同参数的 TypeScript 多个返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40242426/

相关文章:

reactjs - React 中的 typescript : Props type check is not working

angular - 从 typescript 中提取 $localize 消息在 Angular 9 中不起作用

angular - 函数内的函数不是函数并且未定义

javascript - 将结果存储在变量中,就像 Java 在 TypeScript 中一样

javascript - Visual Studio 无法识别导入的 npm 包?

javascript - 如何在模板中显示数据

javascript - Angular - 监听特定的 DOM 插入,然后监听滚动事件

typescript - 泛型:TS2345 'T[keyof T]' 类型的参数不可分配给 'Date' 类型的参数,其中 <T extends {}>

javascript - Angular 2.0 和 TypeScript - 从多维数组对象填充 <select> 选项

angular - 从 Angular 2 上的查询参数中预填充输入文本框