Maximus - 8 months ago 75
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

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?

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.