- 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.
推薦閱讀
- Cocos2d Cross-Platform Game Development Cookbook(Second Edition)
- 現代C++編程:從入門到實踐
- Spring Cloud Alibaba核心技術與實戰案例
- 架構不再難(全5冊)
- Apache Karaf Cookbook
- Ext JS 4 Web Application Development Cookbook
- Node.js Design Patterns
- C/C++程序員面試指南
- Python 3.7從入門到精通(視頻教學版)
- Hands-On Kubernetes on Windows
- Building Serverless Web Applications
- Redmine Cookbook
- Node.js實戰:分布式系統中的后端服務開發
- 體驗之道:從需求到實踐的用戶體驗實戰
- HikariCP數據庫連接池實戰