一个待办任务债台高筑的夜晚,偷懒和家人共处了一小段家庭时间之后,还是不愿意开始消灭TODO LIST。往往这个时候会掏出手机打发一下时间,见微信群中有发 https://dev.to/ 是个不错的网站。索性用自己碎片时间翻译一些文章。这篇文章作者是:Jeremy Likness 微软的工程师,他想写一篇如何用Typescript开发Node.js,文章比较简单,作者给出来一个小视频来讲解。通过这篇文章,可以快速了解快速上手Typescript开发Node.js

几年前,我应邀参加了一次分享,分享主题是帮助Node.js 开发人员通过拥抱TypeScript 来更好的增强Javascript 所带来的益处。非常幸运的是其中有一位听众David Neal,他是位才华横溢的艺术家,会议期间创作了一幅草图来总结我的分享。

推文见: David Neal 🥓🥑 的 Twitter: “TypeScript for Node.js @jeremylikness #visualnotes #connecttech17… ”
完整的分享文稿和代码参见:GitHub - JeremyLikness/typescript-for-node: Presentation materials for Connect.Tech 2017. Covers building Node.js apps with TypeScript.
我录了以视频来阐述这些概念。 在不到十分钟的时间内,我来演示下如何从零开始用TypeScript构建一个Node.js 应用。 看吧,也让我了解下你的想法。
简短的记录下视频教程
初始化项目
mkdir MakeThingscd MakeThingsnpm init -y
安装依赖
npm i typescript @types/node -D
初始化tsconfig.json
node node_modules/typescript/lib/tsc --init
创建common.ts
mkdir src && touch src/common.ts
common.ts
export interface INamed {name: string}
创建animal.ts
touch src/animal.ts
common.ts
import { INamed } from ‘./common’export class Animal implements INamed {constructor(public name: string) {}}export class Animals extends Array<Animal> {constructor() {super();[‘Lynx’, ‘Jaguar’, ‘Panther’, ‘Leopard’, ‘Tiger’, ‘Lion’].forEach(name => {this.push(new Animal(name))})}}
修改tsconfig.json 只罗列出了修改部分
{“compilerOptions”: {“declaration”: true,“sourceMap”: true,“outDir”: “./lib”“rootDir”: “./src”}}
修改package.json
“scripts”: {“test”: “echo \”Error: no test specified\” && exit 1”,“build”: “tsc”},
尝试执行
npm run build
这时候会把ts代码 打到 lib目录下

在src 继续添加一些代码
color.ts
import { INamed } from ‘./common’export class Color implements INamed {constructor(public name: string) {}}export class Colors extends Array<Color> {constructor() {super();[‘Red’, ‘Orange’, ‘Yellow’, ‘Green’, ‘Blue’, ‘Indigo’, ‘Violet’].forEach(color => this.push(new Color(color)))}}
thing.ts
import { INamed } from ‘./common’import { Animal } from ‘./animal’import { Color } from ‘./color’export class Thing implements INamed {private _animal: Animalprivate _color: Colorpublic get animal(): Animal {return this._animal}public get color(): Color {return this._color}public get name(): string {return `${this._color.name} ${this._animal.name}`}constructor(color: Color, animal: Animal) {this._animal = animalthis._color = color}}function pickOne<T>(list: Array<T>): T {var idx = Math.floor(Math.random() * list.length)return list[idx]}export var makeThing = (colorList: Array<Color>, animalList: Array<Animal>) => {return new Thing(pickOne(colorList), pickOne(animalList))}
main.ts
import { Animals } from ‘./animal’import { Colors } from ‘./color’import { makeThing } from ‘./thing’var colors = new Colors()var animals = new Animals();[1, 2, 3, 4, 5].forEach(() => {console.log(makeThing(colors, animals).name)})
运行 npm run build 把Ts代码编译成js代码
最后运行 node lib/main.js

代码见:typescript-for-node/TypeScriptProject at master · JeremyLikness/typescript-for-node · GitHub
为了方便墙内的同学看上传视频到B站

