- Learn React with TypeScript 3
- Carl Rippon
- 320字
- 2021-06-10 19:16:33
Objects
The object type is shared with JavaScript and represents a non-primitive type. Objects can contain typed properties to hold bits of information.
Let's work through an example:
- Let's enter the following code into the TypeScript playground, which creates an object with several properties of information:
const customer = {
name: "Lamps Ltd",
turnover: 2000134,
active: true
};
If we hover over name, turnover, and active, we'll see that TypeScript has smartly inferred the types to be string, number, and boolean respectively.
- If we hover over the customer variable name, we see something interesting:
- Rather than the type being object, it is a specific type with name, turnover, and active properties. On the next line, let's set the turnover property to some other value:
customer.turnover = 500000;
As we type the turnover property, IntelliSense provides the properties that are available on the object:
- This line of code is perfectly fine, so we don't get any complaints from the compiler. If we set the turnover to a value that has an incorrect type, we'll be warned as we would expect:
- Now let's set a property on customer that doesn't exist yet:
customer.profit = 10000;
We'll see that TypeScript complains:
This makes sense if we think about it. We've declared customer with name, turnover, and active properties, so setting a profit property should cause an error. If we wanted a profit property, we should have declared it in the original declaration.
In summary, the object type is flexible because we get to define any properties we require, but TypeScript will narrow down the type to prevent us incorrectly typing a property name.
- 新編Visual Basic程序設計上機實驗教程
- Learning Selenium Testing Tools with Python
- AIRAndroid應用開發(fā)實戰(zhàn)
- UI智能化與前端智能化:工程技術、實現(xiàn)方法與編程思想
- 21天學通C++(第6版)
- 精通Python設計模式(第2版)
- Python Data Analysis Cookbook
- Mastering Business Intelligence with MicroStrategy
- R用戶Python學習指南:數(shù)據(jù)科學方法
- 現(xiàn)代C++編程實戰(zhàn):132個核心技巧示例(原書第2版)
- Spring Boot+MVC實戰(zhàn)指南
- R語言數(shù)據(jù)可視化:科技圖表繪制
- Everyday Data Structures
- Vue.js光速入門及企業(yè)項目開發(fā)實戰(zhàn)
- Learning Python Data Visualization