课程表

TypeScript课程

工具箱
速查手册

TypeScript 接口

当前位置:免费教程 » JS/JS库/框架 » TypeScript

接下来,我们通过一个接口来扩展以上实例,创建一个 interface.ts 文件,修改 index.html 的 js 文件为 interface.js。interface.js 文件代码如下:

  1. interface Shape {
  2. name: string;
  3. width: number;
  4. height: number;
  5. color?: string;
  6. }
  7. function area(shape : Shape) {
  8. var area = shape.width * shape.height;
  9. return "I'm " + shape.name + " with area " + area + " cm squared";
  10. }
  11. console.log( area( {name: "rectangle", width: 30, height: 15} ) );
  12. console.log( area( {name: "square", width: 30, height: 30, color: "blue"} ) );

接口可以作为一个类型批注。

编译以上代码 tsc interface.ts 不会出现错误,但是如果你在以上代码后面添加缺失 name 参数的语句则在编译时会报错:

  1. console.log( area( {width: 30, height: 15} ) );

重新编译,错误信息如下:

  1. $ tsc hello.ts
  2. hello.ts(15,20): error TS2345: Argument of type '{ width: number; height: number; }' is not assignable to parameter of type 'Shape'.
  3. Property 'name' is missing in type '{ width: number; height: number; }'.

浏览器访问,输出结果如下:

结果
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号