Typescript 官方文档起的这个噱头名字:TypeScript in 5 minutes,虽然光看完文章就不止5分钟。走完整个文档流水账如下(代码编辑器用的是VS Code)
第一个 TypeScript 程序
运行
tsc 问好.ts
编译生成“问好.js”文件。
添加参数类型
如果'那谁'的类型不符,比如是数组类型[0,1,2],编译时会报错,挺好:
问好.ts(7,30): error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.
添加接口
这里路人的“形状”符合“人”,类型就被判定为相符。
自己误写成了:
编译提示‘人’是个类型而不是值,挺好:
问好.ts(7,20): error TS2693: '人' only refers to a type, but is being used as a value here.
添加类
官方文档说添加 class 之后编译生成的 js 文件与没有 class 的相同,这里不解,实验结果是不同的。
运行第一个网络应用
为了检验 js 文件,添加HTML文件:
最后一个插曲:
html 文件在 Chrome 中打开显示正确:
吃了么, 大黄
但在火狐(Firefox)浏览器中打开时报错:
The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.%E9%97%AE%E5%A5%BD.html
将View->TextEncoding从Western改为Unicode后显示正确。
更多中文编程推广过程内情,请关注“用中文编程”微信公众号。