- 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.
推薦閱讀
- Oracle 11g從入門到精通(第2版) (軟件開發視頻大講堂)
- Drupal 8 Blueprints
- C語言程序設計案例教程(第2版)
- HBase從入門到實戰
- Building an RPG with Unity 2018
- 精通Linux(第2版)
- Python忍者秘籍
- Angular開發入門與實戰
- Yii Project Blueprints
- Learning Continuous Integration with TeamCity
- Spring+Spring MVC+MyBatis從零開始學
- Moodle 3 Administration(Third Edition)
- DB2SQL性能調優秘笈
- PostgreSQL Developer's Guide
- SAP Web Dynpro for ABAP開發技術詳解:基礎應用