- Learn React with TypeScript 3
- Carl Rippon
- 220字
- 2021-06-10 19:16:34
Properties
Properties are one of the elements that can be part of an interface. Properties can hold values associated with an object. So, when we define a property in an interface, we are saying that objects that implement the interface must have the property we have defined.
Let's start to play with an interface in the TypeScript playground:
- Enter the following interface:
interface Product {
name: string;
unitPrice: number;
}
- The preceding example creates a Product interface with name and unitPrice properties. Let's go on to use this interface by using it as the type for a table variable:
const table: Product = {
name: "Table",
unitPrice: 500
}
- Let's try to set a property that doesn't exist in the interface:
const chair: Product = {
productName: "Table",
price: 70
}
As expected, we get a type error:
- Properties on an interface can reference another interface because an interface is just a type. The following example shows an OrderDetail interface making use of a Product interface:
interface Product {
name: string;
unitPrice: number;
}
interface OrderDetail {
product: Product;
quantity: number;
}
const table: Product = {
name: "Table",
unitPrice: 500
}
const tableOrder: OrderDetail = {
product: table,
quantity: 1
};
This gives us the flexibility to create complex object structures, which is critical when writing large, complex apps.
推薦閱讀
- Learning RxJava
- Vue.js入門與商城開發實戰
- 三維圖形化C++趣味編程
- Network Automation Cookbook
- YARN Essentials
- 高級語言程序設計(C語言版):基于計算思維能力培養
- Apache Kafka Quick Start Guide
- Haskell Data Analysis Cookbook
- Android開發三劍客:UML、模式與測試
- C語言程序設計習題與實驗指導
- PHP 7從零基礎到項目實戰
- Advanced UFT 12 for Test Engineers Cookbook
- 零基礎學Python編程(少兒趣味版)
- 深入理解BootLoader
- PyQt編程快速上手