type
キーワードを使用していますが、インターフェイスに関するドキュメントは各例に適用されます。 type
とinterface
は同じ方法で動作しますが、遺産にはtype
を使用できません。
インデクサ
は、任意の文字列のキーを持つマップを許可します。以下の例では、キーは文字列(numbers are also allowed)でなければなりません。これは明示的に指定することはできませんが、技術的にはid: string | number
です。値は文字列(および文字列のみ)でなければなりません。
// Defines an indexer
// The id(or key) must be a string, or number.
// The value must be a string.
type TypeOne = { [id: string]: string; };
const a: TypeOne = {};
a['key'] = 'value';
// Example type violation Type '3' is not assignable to type 'string'
a['key'] = 3;
インデクサーはハンドブックのinterface sectionに記載されています。
オブジェクト
質問の2番目のタイプはオブジェクト構造です。適切に型付けされた値を持つ名前付きプロパティを持つオブジェクトが必要です。リテラルを使用して型のインスタンスを作成するときは、不正解のスペルをキャッチするのに役立つ未知のプロパティ(許可されていない)を使用します。あなたの質問で
type TypeTwo = { id: string; };
const a: TypeTwo = {
id: 'value'
}
// Object literal must only specify known values
const b: TypeTwo = {
id: 'value',
nmae: 'value'
}
// Type 'number' is not assignable to type 'string'.
const c: TypeTwo = {
id: 4
}
機能
第三のタイプは、機能を説明しています。例b
の時々不思議なケースを含む以下の例は、id
パラメータを持たなくても有効です。その1つのロジックは、関数本体のパラメータを無視すると、それを強制的に署名に入れる理由です。コーリングコードがそれを供給するかもしれませんが、あなたはそれをとにかく使っていません。
type TypeThree = (id: string) => string;
const a: TypeThree = (id: string) => {
return id;
};
const b: TypeThree =() => {
return 'value';
}
// Types of parameters 'id' and 'id' are incompatible.
const c: TypeThree = (id: number) => {
return 'value';
}
// Type 'number' is not assignable to type 'string'.
const d: TypeThree = (id: string) => {
return 5;
}
ハンドブックのfunction typesを参照してください。
ランダムに試してセマンティクスを推論しようとするよりも、*構文を導入し説明する*を読んで*始めるのは簡単ではないでしょうか?一つは、これら3つの配列のいずれも配列を定義していないので、その後、変数*をそれらの配列の配列として入力します*。任意のキー、キーIDを持つオブジェクト、および関数を持つオブジェクトを定義しました。例えば、 https://www.typescriptlang.org/docs/handbook/interfaces.html – jonrsharpe