TypeScript multiple return types with identical parameters
To add to Erik's reply. In the last line of his second example, instead of redeclaring the type, you could use the "as" keyword.
let customObj = a.testMethod(false) as CustomType;
So basically, if you have a function that has multiple return types, you could specify which of the types should be assigned to a variable by using the "as" keyword.
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;
});
Ok, this is the right way if you want to have proper types:
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 };
}
More general example
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