LoginSignup
0
0

More than 3 years have passed since last update.

Typescript 奮闘記 No.01 『Interface編』

Posted at

備忘録として TypeScriptのインプットをまとめていく.

Objectの構造を定義するもの

type alias, interface, class ってやつがある。

とりあえず Interface を勉強した

Interface

Property

interface Item {
    name: string;
    price: number;
}

Customer の Interface は name と age の プロパティが定義されている。
Interfaceでプロパティを定義すると、そのInterfaceを実装するオブジェクトは 定義されたプロパティを持たなければならない、という制約を掛ける事ができる。

const pencil: Item = {
    name: "鉛筆",
    price: 110
}
// price か name のどちらかが制限されてなければエラーになる

Interface は 型なので、別のInterfaceから参照する事もできる

interface SaleRow {
    item: Item
    total: number
}

method

また、メソッドの構造も定義できる。ただし、メソッドの実装を定義するものではない。

interface Item {
    name: string;
    price: number;
    getDiscountPrice(discountRate: number): number;
}

ここで以下のように認識しておくと良い

  • パラメータの型さえ同じなら、実は discountRate の部分を discountPercentage とかに変えても動く
  • でも、メソッド名を変更したり、パラメータの型や戻り値の型を変えるとコンパイルは通らない
  • 上記の事もあって、Interfaceにて メソッドを定義する場合は、パラメータ名を定義しない事も慣習としてある。
interface Item {
    name: string;
    price: number;
    getDiscountPrice(number): number;
}

Option

interface Item {
    name: string;
    price: number;
    image?: string;
    getDiscountPrice(discountRate: number): number;
}

上記のように ? をつけて宣言する事で、Optionalの型を定義できる

Readonly

  • プロパティの前に readonly キーワードを使用する事で、最初に設定された後にプロパティが更新できないようにする.

Extend

既にあるInterfaceについて それを拡張して新しいInterfaceを再定義する事もできる。

interface Item {
    name: string;
    price: number;
}

interface Item {
    tags: string[];
}

// Item は name, price, tags をプロパティに持つInterfaceとなる
interface Item {
    name: string;
    price: number;
}

interface SpecialItem extends Item {
    specialPrice: number;
}

// SpecialItem は name, price, specialPrice をプロパティに持つInterfaceとなる
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0