Maximus Maximus - 2 years ago 150
TypeScript Question

Validating function signature - interface vs type alias

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 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};

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?

Answer Source

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 can interfaces 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download