Skip to content

Instantly share code, notes, and snippets.

@francoisgeorgy
Created March 22, 2020 20:08
Show Gist options
  • Select an option

  • Save francoisgeorgy/4e2c32471ca170d6caae68b378966874 to your computer and use it in GitHub Desktop.

Select an option

Save francoisgeorgy/4e2c32471ca170d6caae68b378966874 to your computer and use it in GitHub Desktop.
#typescript interfaces vs types
//extending interfaces
interface PartialPointX { x: number; }
interface Point extends PartialPointX { y: number; }
//extending types
type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };
// Interface extends type
type PartialPointX = { x: number; };
interface Point extends PartialPointX { y: number; }
//Type alias extends interfaces
interface PartialPointX { x: number; }
type Point = PartialPointX & { y: number; };
//defining the interface for objects
interface Point {
x: number;
y: number;
}
//using types as well
type Point2 = {
x: number;
y: number;
};
//implementing the Interface
class SomePoint implements Point {
x: 1;
y: 2;
}
//Implementing the Type alias
class SomePoint2 implements Point2 {
x: 1;
y: 2;
}
type PartialPoint = { x: number; } | { y: number; };
// This is the only thing you can't do: implement a union type
class SomePartialPoint implements PartialPoint {
x: 1;
y: 2;
}
// The only extra feature Interfaces bring to the table (that Type aliases don’t),
// is “declaration merging” which means you can define the same interface several
// times and with each definition, the properties get merged:
interface Point { x: number; } //declaration #1
interface Point { y: number; } //declaration #2
// These two declarations become:
// interface Point { x: number; y: number; }
const point: Point = { x: 1, y: 2 };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment