TypeScript 是 JavaScript 的超集,由微软公司在 2012 年正式发布。
环境搭建: npm install -g typescript
1、运行HelloWorld 新建demo1.ts并写入如下代码

运行 node demo1.ts会报错
需运行 “tsc demo1.ts” 将ts文件转换为js文件,“node demo1.js”,即可打印HelloWorld。
或者安装可以运行ts的插件 npm install -g ts-node,安装后执行“ts-node xxx.ts”
2、静态类型
基础静态类型:“变量命名:类型” const count: number =1;

3、函数定义
注解
类型注解(type annotation):常用于方法中,来定义参数类型,参见add
类型推断(type inferrence):ts会自动推断出one是数字类型 const one = 123
参数
可选参数 stature?: string
有默认值的参数 stature: string='水桶腰'
对象类型参数:function add({one, two}:{one:number, two:number}) {}
返回值
void 返回值为空
never 永远执行不完
函数定义的方法

4、接口、类型别名和引用类型
接口和类型别名功能相似,可根据自己喜好使用
接口参数可增加任意类型: [propname: string]: any;
类型别名: type Person = { name: string, age: number }
const pers: Person[] = [
{ name: 'adkl', age: 23 }, { name: 'adkl', age: 23 },
]

引用类型: 数组,String, Data, RegExp

5、类 — 关键字的使用和java一样
抽象类:abstract classGirl { abstract skill() }
因为没有具体的方法,所以我们这里不写括号,子类中必须做方法的实现
范围修饰符 private 只允许在类的内部被调用
范围修饰符 protected 只允许在类内及继承的子类中使用
范围修饰符 public(默认值) 在内部外部都可以访问
属性修饰符 readonly 只可读取,不可修改

类的继承使用关键字:extends
子类constructor方法中:必须调用super();

6、命名空间

网友评论