2

I have the following function:

function (n: number) {
    return {s: n};
}

I need to create a validator for the signature. From what I've read I have two options:

Interface

interface ValidatorFnInterface {
    (n: number): {
        [key: string]: any;
    };
}

Type alias

type ValidatorFnType = (n: number) => {
    [key: string]: any
};

And they can be used like this:

let f1: ValidatorFnInterface = function (n: number) {
    return {s: n};
};

let f2: ValidatorFnType = function (n: number) {
    return {s: n};
};

Typescript lib.d.ts seems to be using type aliases, while angular2 code seems to be using interface. My question is when to use what? Is there any logic I should use when deciding or is it a matter of preference?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • Possible duplicate of [Typescript: Interfaces vs Types](https://stackoverflow.com/questions/37233735/typescript-interfaces-vs-types) – chharvey Aug 12 '18 at 01:04

1 Answers1

5

Currently classes in TypeScript can only implement interfaces not arbitrary types. So in general, if you want other classes to be able to use your types as something to implement, you should use interfaces. Likewise interfaces can only extend other interfaces.

On the negative side for interfaces, they can not express intersection or union types, so if you want that in one single type you're stuck with type aliases.

aleclarson
  • 18,087
  • 14
  • 64
  • 91
Alex
  • 14,104
  • 11
  • 54
  • 77
  • thanks, so what you're saying you would stick to interfaces for functions signature validation? – Max Koretskyi Nov 25 '16 at 16:20
  • @Maximus That depends on your requirements. I personally like to express my types with type aliases because it feels cleaner. But interfaces are probably a safer bet, and more reusable. – Alex Nov 25 '16 at 16:34
  • thanks. Did type alias appear later in the language than interfaces? Maybe that's the reason why angular2 uses interfaces. Also, what can you say about [this](http://stackoverflow.com/questions/13137350/defining-typescript-callback-type#comment47535906_14249517) comment? – Max Koretskyi Nov 25 '16 at 16:48