TypeScript 接口
接下来,我们通过一个接口来扩展以上实例,创建一个 interface.ts 文件,修改 index.html 的 js 文件为 interface.js。interface.js 文件代码如下:
- interface Shape {
- name: string;
- width: number;
- height: number;
- color?: string;
- }
- function area(shape : Shape) {
- var area = shape.width * shape.height;
- return "I'm " + shape.name + " with area " + area + " cm squared";
- }
- console.log( area( {name: "rectangle", width: 30, height: 15} ) );
- console.log( area( {name: "square", width: 30, height: 30, color: "blue"} ) );
接口可以作为一个类型批注。
编译以上代码 tsc interface.ts 不会出现错误,但是如果你在以上代码后面添加缺失 name 参数的语句则在编译时会报错:
- console.log( area( {width: 30, height: 15} ) );
重新编译,错误信息如下:
- $ tsc hello.ts
- hello.ts(15,20): error TS2345: Argument of type '{ width: number; height: number; }' is not assignable to parameter of type 'Shape'.
- Property 'name' is missing in type '{ width: number; height: number; }'.
浏览器访问,输出结果如下:

转载本站内容时,请务必注明来自W3xue,违者必究。