Type Scriptインタフェース

1322 ワード

インタフェース定義
interface Person {
    name: string
    age: number
}
function print(p: Person) {
    console.log(p.name);
    console.log(p.age);
}
let persion = {age:10, name:"  "};
print(person)

タイプインスペクターは、対応するプロパティが存在し、タイプが一致している限り、プロパティの順序をチェックしません.
オプション属性
interface SquareConfig {
    color?: string
    width?: number
}

オプション属性を定義するには、属性の後に?を付けるだけです.
読み取り専用プロパティ
一部のオブジェクト属性は、オブジェクトが作成されたときにのみ属性の値を変更でき、readonlyで読み取り専用属性を指定できます.
interface Point {
    readonly x;
    readonly y;
}
readonlyconstの違いは、主に1つが変数に対して1つがオブジェクトに対する属性であることにある.
属性チェック
interface SquareConfig {
    color?: string;
    width?: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
    // ...
}

let mySquare = createSquare({ colour: "red", width: 100 });

オブジェクトのフォント量に「ターゲットタイプ」に含まれない属性がある場合、エラーが発生します.2つの方法で誤報を避けることができます.タイプブレークスルー
let mySquare = createSquare({colour: "red", width: 100} as SquareConfig);

索引の署名
interface SquareConfig {
    color?: string;
    width?: number;
    [propName: string]: any
}

オブジェクトに任意の数の他のプロパティがある可能性があることを示します.