msa*_*ord 10 typescript angular2-forms typescript2.0
为了进入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*/ };
Run Code Online (Sandbox Code Playgroud)
我也知道我可以返回一个类型(如Promise),它本身可以是多个子类型:
private active(): Promise<void|null> { ... }
Run Code Online (Sandbox Code Playgroud)
但是,在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 };
}
Run Code Online (Sandbox Code Playgroud)
也没做
private lowercaseValidator(c: FormControl): null|Object {...}
private lowercaseValidator(c: FormControl): <null|Object> {...}
Run Code Online (Sandbox Code Playgroud)
(有趣的是,我得到了以下错误,而不是更多信息:
error TS1110: Type expected.
error TS1005: ':' expected.
error TS1005: ',' expected.
error TS1128: Declaration or statement expected.
Run Code Online (Sandbox Code Playgroud)
)
我离开只是使用
private lowercaseValidator(c: FormControl): any { ... }
Run Code Online (Sandbox Code Playgroud)
这似乎否定了具有类型签名的优势?
虽然这个问题的灵感来自于由框架直接处理的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 };
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
添加到埃里克的回复中。在他的第二个示例的最后一行中,您可以使用“as”关键字,而不是重新声明类型。
let customObj = a.testMethod(false) as CustomType;
Run Code Online (Sandbox Code Playgroud)
因此基本上,如果您有一个具有多个返回类型的函数,您可以使用“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;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13822 次 |
| 最近记录: |