?TypeScript入门基本相当于一门和C#语言的东西了,比较漫长的入门过程。
最大的一个门槛,就是 TypeScript 最后编译成 JavaScript。调用别人的库也是用 JavaScript?方式存在的。
TypeScript和JavaScript的协作就需要.d.ts文件了。
查看已经安装的包
npm ls -g --depth 0
tsd本来是安装类型文件的,废弃了,建议typings
typings也废弃了,建议用这样的格式安装?
npm install --save @types/node
使用例子
我们通过给node增加类型包来举例,开发一个继承EventEmitter的类的例子。
npm install --save @types/node
这个@types是一个npm发布用户的意思。
涉及文件 .vscode/launch.json、.vscode/tasks.json、package.json、.package-lock.json、tsconfig.json?等
参考?
压缩包下载
launch.json? (VSCode菜单Debug -> Add Configuration)
{
// For more information, visit: https://go.microsoft测试数据/fwlink/?linkid=830387
" version " : " 0.2.0 " ,
" configurations " : [
{
" type " : " node " ,
" request " : " launch " ,
" name " : " Launch Program " ,
" program " : " ${workspaceFolder}\\bin\\index.js " ,
// "preLaunchTask": "build ts",
// "cwd": "${workspaceFolder}/./bin", // 修改执行node index.js 的路径
" console " : " internalConsole " , // 输出到 DEBUG CONSOLE (默认值)
" internalConsoleOptions " : " openOnSessionStart " , // 每次运行自动转到 DEBUG CONSOLE 以显示输出内容
" outFiles " : [
" ${workspaceFolder}/**/*.js "
]
}
]
}
?
tasks.json? (VSCode菜单?Terminal -> Configure Default Build Task)
{
// See https://go.microsoft测试数据/fwlink/?LinkId=733558
" version " : " 2.0.0 " ,
" tasks " : [
{
" label " : " build ts " ,
" type " : " typescript " ,
" tsconfig " : " tsconfig.json " ,
" problemMatcher " : [
" $tsc "
],
" group " : {
" kind " : " build " ,
" isDefault " : true
}
}
]
}
?
package-lock.json
package.json? (npm init?和?npm install?npm install --save @types/node)
tsconfig.json? (tcs -init)
{
" compilerOptions " : {
" target " : " es5 " , /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
" module " : " umd " , /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
" outDir " : " bin " , /* Redirect output structure to the directory. */
" strict " : true , /* Enable all strict type-checking options. */
" sourceMap " : true ,
// "baseUrl": "ts", // 不要这个设置,会导致自动生成的import语句缺少./部分,运行时报找不到模块出错
// "esModuleInterop": true,
// "moduleResolution": "node"
}
}
?
ts/index.ts? 实现源码
console.log( " 执行路径: " + process.cwd());
// CTRL + Shift + Y 显示 DEBUG CONSOLE
import { EventEmitter } from " events " ;
import { N1 } from " ./utils " ;
class MyEmitter extends EventEmitter
{
}
let my = new MyEmitter();
my.on( " abc " , (a1, a2)=> {
console.log( " event, " + a1 + " , " + a2 + " , " + new Date());
});
my.emit( " abc " , " 第一个参数 " , " 第二个参数 " );
let r = N1.C1.Add1( 10 , 20 );
console.log(r);
?
ts/utils.ts
export namespace N1
{
export class C1
{
public static Add1(a:number, b:number)
{
return a * 10 + b * 100 ;
}
}
}
?
?
查看更多关于TypeScript 及类型库 tsd typings @types/XXX 入门的详细内容...