ts的安装
npm install typescript -g
ts-node
的安装使用,可用于编译ts文件
npm install -g ts-node
ts-node demo.ts
tsc demo.ts
命令会编辑demo.ts为demo.js文件
Static Typing 静态类型
基础静态类型 null undefined boolean void symbol
const count: number = 1;
自定义静态类型
interface test {
uname: String,
age: number
}
const test1 :test = {
uname : '小孩',
age: 12
}
console.log(test1)
//对象静态类型
const xx :{
name: string,
age: number
} = {
name: '小盒',
age: 11
}
// 数组类型
const xx1 : string [] = ['测试' ,'猜测是', '测试库']
// 类类型
class Person{}
const ceshi : Person = new Person()
// 函数类型
const demos : ()=> String = ()=>{ return '测试'}
类型注解和类型推断
类型注解
: 给变量定义基础类型
类型推断
: 你的代码 TS 会自动的去尝试分析变量的类型。
如果 TS
无法分析变量类型的话, 我们就需要使用类型注解
tsconfig.json文件详解
命令tsc --init
生成tsconfig.json文件,命令 npm init -y
生成package.json 配置文件
注
:该配置文件不支持单引号
1、include 、exclude、files的不同
“include” : [“demo.ts”] 指定编译的文件,目录
“exclude” : [ “demo.ts”] 指定不
编译的文件,目录
“files” : [“demo.ts”] 指定编译的文件 ,目录
不同:
- include包含的文件会被exclude排除编译
- files包含的文件
不
会被exclude排除编译
2、compilerOptions 配置项
removeComments:true
编译ts为js时注释代码不显示
noImplicitAny:true
当必须明确注解类型为any的值
function demo(name: any) {
return name;
}
strictNullChecks: false
不强制检查 NULL 类型, 如果设置为true时则下列代码会报错
const jspang: string = null;
noUnusedLocals:true
未使用的变量打包时会在控制台进行提示
3、rootDir和outDir
{
"outDir": "./dist" , //打包文件
"rootDir": "./src" , //编辑文件
}
4、target和allowJs
"target":'es5' , // 这一项默认是开启的,你必须要保证它的开启,才能转换成功
"allowJs":true, // 这个配置项的意思是联通
详解:https://www.tslang.cn/docs/handbook/compiler-options.html
泛型
一般用 <T>
代表
function join<T, P>(first: T, second: P) {
return `${first}${second}`;
}
join < number, string > (1, "2");
详转:https://blog.csdn.net/weixin_44761091/article/details/124017662
命名空间 namespace
namespace xxx{
}
parcel打包
安装parcel
yarn add -dev parcel@next
命令 yarn test
打包