- 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.
推薦閱讀
- What's New in TensorFlow 2.0
- Spring技術內幕:深入解析Spring架構與設計
- Python從菜鳥到高手(第2版)
- 深度學習:算法入門與Keras編程實踐
- Java編程技術與項目實戰(第2版)
- Scala編程實戰(原書第2版)
- 高級語言程序設計(C語言版):基于計算思維能力培養
- Python算法從菜鳥到達人
- ANSYS Fluent 二次開發指南
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(1)
- Mastering Xamarin.Forms(Second Edition)
- Java面向對象程序設計
- Android項目實戰:手機安全衛士開發案例解析
- 智能手機APP UI設計與應用任務教程
- Qt 4開發實踐