# TypeScript - Interface ###### tags: `TypeScript` [TOC] ## Interface 是什麼? - Interface 被稱作介面或接口 - 在 TypeScript 中,我們可以利用`interface` 來規範物件的型別。 ## 基礎範例 ```typescript= interface Person { name: string; age: number; } function greet(person: Person) { return "Hello " + person.name; } ``` 我們用介面`Person` 來規範物件:必須要有屬性 `name`(型別為 string) 和 `age` (型別為 number)。 ## Optional Property 在屬性後面加個 `?`,代表此屬性非必填,可以被忽略。 下方 `SquareConfig` 的 `color` 和 `width` 屬性,可以不必被實作 ```typescript= interface SquareConfig { color?: string; width?: number; } function createSquare(config: SquareConfig): { color: string; area: number } { let newSquare = { color: "white", area: 100 }; if (config.color) { newSquare.color = config.color; } if (config.width) { newSquare.area = config.width * config.width; } return newSquare; } let mySquare = createSquare({ color: "black" }); ``` ## 規範 Class 的行為 Interfaces 可用來規範 class 的屬性(property) 和方法 (method) ```typescript= interface IPerson { name: string; eat(): void; } ``` 介面 `IPerson` 描述了屬性 `name` 的型別和方法`eat` 的行為,但他並沒有撰寫關於 name 和 eat 是什麼或怎麼執行的程式碼,因為 Interface 只做描述,不做動作。 ```typescript= class Person implements IPerson { name: string; constructor(name: string) { this.name = name; } eat(): void { console.log(`${this.name} 在吃東西`) } } const tom = new Person('Tom'); console.log(tom.eat()); // Tom 在吃東西 ``` Class 會用 `implements` 指定要實作的 Interface ,只要指定了,就一定要把 Interface 內所有的 Method 和 Property 給實作 --- --- 假設我沒有實作方法 `eat` 的內容,程式就會報錯。 ## Reference - [TypeScript 官方指南 - Objects](https://www.typescriptlang.org/docs/handbook/2/objects.html) - [TypeScript | 從 TS 開始學習物件導向 - Interface 用法](https://medium.com/enjoy-life-enjoy-coding/typescript-%E5%BE%9E-ts-%E9%96%8B%E5%A7%8B%E5%AD%B8%E7%BF%92%E7%89%A9%E4%BB%B6%E5%B0%8E%E5%90%91-interface-%E7%94%A8%E6%B3%95-77fd0959769f)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up