官术网_书友最值得收藏!

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:

  1. 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.

  1. 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));
Note that you can execute all of the sample files by typing the command
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.

主站蜘蛛池模板: 衡阳县| 井冈山市| 莱阳市| 巴彦淖尔市| 莱芜市| 怀化市| 承德县| 洛隆县| 随州市| 项城市| 清新县| 大新县| 固安县| 蓬莱市| 鹤庆县| 莱州市| 盐津县| 邹城市| 阿拉善右旗| 松原市| 铜川市| 闸北区| 道孚县| 九龙城区| 永康市| 大埔县| 毕节市| 延川县| 文山县| 清苑县| 新乐市| 永嘉县| 寿宁县| 武乡县| 黑河市| 苏尼特左旗| 固阳县| 宁城县| 班玛县| 丰都县| 上饶市|