次の違いは何ですか?
type Foo = {
foo: string
};
interface Foo {
foo: string;
}
次の違いは何ですか?
type Foo = {
foo: string
};
interface Foo {
foo: string;
}
回答:
インターフェースは拡張可能
interface A {
x: number;
}
interface B extends A {
y: string;
}
そしてまた増強された
interface C {
m: boolean;
}
// ... later ...
interface C {
n: number;
}
ただし、型のエイリアスは、インターフェイスではできないことを表すことができます
type NumOrStr = number | string;
type NeatAndCool = Neat & Cool;
type JustSomeOtherName = SomeType;
したがって、一般に、質問に示されているように、単純なオブジェクトタイプしかない場合は、通常、インターフェイスの方が優れています。インターフェースとしては書き込めないものを書きたい、または単に別の名前を付けたいだけの場合は、型エイリアスの方が適しています。
Type aliases, however, can represent some things interfaces can't私にはあなたの例のようでNeatAndCoolありJustSomeOtherName、既存のNeat、CoolまたはSomeTypeタイプを拡張するインターフェースとして作成できます。
interface NeatAndCool extends Neat, Cool {} interface JustSomeOtherName extends SomeType {}
また、インターフェースを実装することもできます。
class Thing implements Neat, Cool
型はインターフェイスのようなもので、その逆も同様です。どちらもクラスで実装できます。ただし、重要な違いがいくつかあります。1。Typeがクラスによって実装される場合、Typeに属するプロパティはクラス内で初期化する必要がありますが、Interfaceではプロパティを宣言する必要があります。2. @ryanが言及したように:インターフェースは別のインターフェースを拡張できます。タイプはできません。
type Person = {
name:string;
age:number;
}
// must initialize all props - unlike interface
class Manager implements Person {
name: string = 'John';
age: number = 55;
// can add props and methods
size:string = 'm';
}
const jane : Person = {
name :'Jane',
age:46,
// cannot add more proprs or methods
//size:'s'
}
これらの違いもすでにこのスレッドにあります。
type Foo = {
foo: string
};
interface Foo {
foo: string;
}
ここtype Fooとinterface Fooほとんど同じように見えるので、混乱します。
interface以下のプロパティ(ここではfoo:string)がオブジェクトに存在する必要があるという契約です。
interfaceはありませんclass。言語が多重継承をサポートしていない場合に使用されます。したがってinterface、異なるクラス間で共通の構造になる可能性があります。
class Bar implements Foo {
foo: string;
}
let p: Foo = { foo: 'a string' };
しかし、typeとinterfaceは非常に異なるコンテキストで使用されています。
let foo: Foo;
let today: Date = new Date();
ここtypeのfooあるFooとtodayされますDate。typeof他の変数の情報を保持する変数declerationのようなものです。
typeインターフェース、クラス、関数シグネチャ、他のタイプ、または値(などtype mood = 'Good' | 'Bad')のスーパーセットのようなものです。最後にtype、可能な変数の構造または値について説明します。
typescriptのtypeは、既存の型を参照するために使用されます。のように拡張することはできませんinterface。以下はその例ですtype。
type Money = number;
type FormElem = React.FormEvent<HTMLFormElement>;
type Person = [string, number, number];
タイプでRestとSpreadを使用できます。
type Scores = [string, ...number[]];
let ganeshScore = ["Ganesh", 10, 20, 30]
let binodScore = ["Binod", 10, 20, 30, 40]
一方、インターフェースでは、新しいタイプを作成できます。
interface Person{
name: string,
age: number,
}
Interface can be extended with extends keyword.
interface Todo{
text: string;
complete: boolean;
}
type Tags = [string, string, string]
interface TaggedTodo extends Todo{
tags: Tags
}