gotchajavascriptCritical
In TypeScript, what is the difference between type and interface?
Viewed 0 times
typescriptandbetweenthedifferencetypeinterfacewhat
Problem
What are the differences between the following?
type Foo = {
foo: string
};
interface Foo {
foo: string;
}Solution
Interfaces can be extended
and also augmented (the so-called declaration merging)
Type aliases, however, can represent some things interfaces can't
So in general if you just have a plain object type, as shown in your question, an interface is usually a better approach. If you find yourself wanting to write something that can't be written as an interface, or want to just give something a different name, a type alias is better.
interface A {
x: number;
}
interface B extends A {
y: string;
}
and also augmented (the so-called declaration merging)
interface C {
m: boolean;
}
// ... later ...
interface C {
n: number;
}
Type aliases, however, can represent some things interfaces can't
type NumOrStr = number | string;
type NeatAndCool = Neat & Cool;
type JustSomeOtherName = SomeType;
So in general if you just have a plain object type, as shown in your question, an interface is usually a better approach. If you find yourself wanting to write something that can't be written as an interface, or want to just give something a different name, a type alias is better.
Context
Stack Overflow Q#36782896, score: 171
Revisions (0)
No revisions yet.