- Hands-On Full Stack Web Development with Angular 6 and Laravel 5
- Fernando Monteiro
- 279字
- 2021-07-23 19:18:51
Declaring an interface
Interfaces are our allies when we use TypeScript, since they do not exist in pure JavaScript. They are an efficient way of grouping and typing variables, ensuring that they are always together, maintaining consistent code.
Let's look at a practical way to declare and use an interface:
- In your text editor, create a new file called band-interface.ts, and add the following code:
interface Band {
name: string,
total_members: number
}
To use it, assign the interface to a function type, as in the following example.
- Add the following code right after the interface code, in the band-interface.ts file:
interface Band {
name: string,
total_members: number
}
function unknowBand(band: Band): void {
console.log("This band: " + band.name + ", has: " + band.total_members + " members");
}
Note that here, we are using the Band interface to type our function parameter. So, when we try to use it, we need to keep the same structure in new objects, as in the following example:
// create a band object with the same properties from Band interface:
let newband = {
name: "Black Sabbath",
total_members: 4
}
console.log(unknowBand(newband));
tsc band-interface.ts and the band-interface.js node in your Terminal.
So, if you follow the preceding tip, you will see the same result in your Terminal window:
This band: Black Sabbath, has: 4 members
As you can see, the interfaces in TypeScript are incredible; we can do a lot of things with them. Throughout the course of this book, we will look at some more examples of using interfaces in real web applications.
- Twilio Cookbook
- 工業(yè)控制網(wǎng)絡(luò)安全技術(shù)與實(shí)踐
- 5G承載網(wǎng)網(wǎng)絡(luò)規(guī)劃與組網(wǎng)設(shè)計(jì)
- JBoss EAP6 High Availability
- 計(jì)算機(jī)網(wǎng)絡(luò)安全實(shí)訓(xùn)教程(第二版)
- Drush User’s Guide
- Getting Started with WebRTC
- 網(wǎng)絡(luò)的琴弦:玩轉(zhuǎn)IP看監(jiān)控
- 計(jì)算機(jī)網(wǎng)絡(luò)與通信(第2版)
- 數(shù)字調(diào)制解調(diào)技術(shù)的MATLAB與FPGA實(shí)現(xiàn):Altera/Verilog版(第2版)
- 基于性能的保障理論與方法
- TD-LTE無線網(wǎng)絡(luò)規(guī)劃與設(shè)計(jì)
- 4G小基站系統(tǒng)原理、組網(wǎng)及應(yīng)用
- 紅藍(lán)攻防:構(gòu)建實(shí)戰(zhàn)化網(wǎng)絡(luò)安全防御體系
- 物聯(lián)網(wǎng)場景設(shè)計(jì)與開發(fā)(初級)