Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript multiple return types with identical parameters

Tags:

Background

Trying to get into the spirit of TypeScript, I am writing fully typed signatures in my Components and Services, which extends to my custom validation functions for angular2 forms.

I know that I can overload a function signature, but this requires that the parameters are different for each return type because tsc compiles each signature to a separate function:

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

I also know that I can return a single type (like a Promise) which can itself be of multiple sub-types:

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

However, in the context of angular2 custom form validators, a single signature (one parameter of type FormControl) can return two distinct types: an Object with form errors, or null to indicate the control has no errors.

This, obviously, does not work:

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

Nor do

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

(Interestingly, I get the following errors, rather than something more informative:

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

)

TL;DR

Am I left simply using

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

which would seem to negate the advantage of having type signatures?

More generally, looking forward to ES6

While this question is inspired by angular2 forms validators, which are handled directly by the framework, so you might not care about declaring the return type, it is still generally-applicable, especially given ES6 constructs like function (a, b, ...others) {}

Perhaps it's simply better practice to avoid writing functions that can return multiple types, but it is rather idiomatic, owing to JavaScript's dynamic nature.

References

  • TypeScript function overloading
  • Typescript syntax for a function returning observable or multiple type
  • https://github.com/Microsoft/TypeScript/issues/11700
  • https://github.com/Microsoft/TypeScript/issues/10727 (...spread) {}
  • https://github.com/Microsoft/TypeScript/issues/10571 < , , type>
like image 960
msanford Avatar asked Oct 25 '16 14:10

msanford


2 Answers

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
like image 144
Erik Cupal Avatar answered Sep 27 '22 19:09

Erik Cupal


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;
});
like image 33
Shonubi Korede Avatar answered Sep 27 '22 19:09

Shonubi Korede