Interfaces
An interface declaration is another way to name an object type:
interface Point {
x: number;
y: number;
}
function printCoord(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 100, y: 100 });
Differences Between Type Aliases and Interfaces
Type aliases and interfaces are very similar, and in many cases you can choose between them freely. Almost all features of an interface
are available in type
, the key distinction is that it can be extended.
Interfaces are often used to share common functionality between classes. So they are similar to abstract classes but without any implementation.
Extending Types vs Interfaces
Extending an interface
interface Animal {
name: string;
}
interface Bear extends Animal {
honey: boolean;
}
const bear = getBear();
bear.name;
bear.honey;
Extending a type via intersections
type Animal = {
name: string;
};
type Bear = Animal & {
honey: boolean;
};
const bear = getBear();
bear.name;
bear.honey;
Adding new fields
Adding new fields to an existing interface
interface Window {
title: string;
}
interface Window {
ts: TypeScriptAPI;
}
const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});
A type cannot be changed after being created
type Window = {
title: string;
};
type Window = {
ts: TypeScriptAPI;
};
// Error: Duplicate identifier 'Window'.
Thoughts about Types vs Interfaces
Main takeaways:
- Use types unless you need a specific feature of interfaces
- If you need a type that extends another type => Use an interface
Interfaces as Function Types
Interfaces can also describe function types:
// type AddFn = (a: number, b: number) => number;
interface AddFn {
(a: number, b: number): number;
}
let add: AddFn;
add = (n1: number, n2: number) => {
return n1 + n2;
};
Usually we use type aliases for function types, but interfaces can also be used.