簡體   English   中英

具有相同參數的 TypeScript 多個返回類型

[英]TypeScript multiple return types with identical parameters

背景

為了融入 TypeScript 的精神,我在我的組件和服務中編寫了完全類型化的簽名,這擴展到了我的 angular2 表單的自定義驗證函數。

我知道我可以重載函數簽名,但這要求每個返回類型的參數不同,因為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.

)

TL; 博士

我是否只是使用

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

這似乎否定了擁有類型簽名的優勢?

更一般的,期待 ES6

雖然這個問題的靈感來自於由框架直接處理的 angular2 表單驗證器,因此您可能不關心聲明返回類型,但它仍然普遍適用,尤其是考慮到 ES6 結構,如function (a, b, ...others) {}

也許避免編寫可以返回多種類型的函數只是更好的做法,但由於 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

添加到 Erik 的回復中。 在他的第二個示例的最后一行中,您可以使用“as”關鍵字而不是重新聲明類型。

let customObj = a.testMethod(false) as CustomType;

所以基本上,如果您有一個具有多種返回類型的函數,您可以使用“as”關鍵字指定應將哪些類型分配給變量。

type Person = { name: string; age: number | string };

const employees: Person[] = [
  { name: "John", age: 42},
  { name: "April", age: "N/A" }
];

const canTakeAlcohol = employees.filter(emp => {
  (emp.age as number) > 21;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM