目录
tsc .\xxx.ts 文件 编译成 .js文件
tsc --init 生成tsconfig.json 利用vscode自动编译ts文件;
outDir: './js‘, ts编译后的代码放到js文件中;strict: true; 运行 tsc xxx.ts
接口 interface Iperson {
firstName: string,
lastName: string
}
类 class
1、类型
布尔 boolean
数字 number
字符串 string
undefined
null
数组 (两种写法): let arr1:number[] = [1,2,3,4]
let arr2: Array<number> = [1,2,3,4] 泛型写法
元组类型 let arr3:[string, number,boolean] = ['x', 12, true] 前后一致对应
枚举类型 enum Color {red = 1, green, blue}; let color: Color = Color.red; console.log(Color.red, Color.green); => 0,1; Color[3] = blue
any类型 let str:any = 100; let arr:any[] = [100, 'xxxx', true] 缺点:无类型提示信息
void类型 没有任何类型 函数没有返回值 function func():void {console.log('xxxxxxx')}
object类型 function func(objectVal: object): object { return {name: xx, age:xx }}
联合类型 function func(str: number|string):string { return str.toString()}
类型断言 <string>str; str as string; str 是string类型
类型推断
2、接口(interface)
interface Iperson {
readonly id: number, readonly代表只读
name: string,
age?: number ? 代表可有可无
}
const person: Iperson {
id: 1,
name: ''
}
函数类型
interface ISerchFunc {
(source:string, subString:string): boolean 定义一个调用签名
}
const searchString: ISerchFunc = function (source:string, subString:string): boolean {
return source.search(subString) > 1
}
类类型
interface IFly {
fly()
}
interface ISwim{
swim()
}
interface ImyFlyAndSwim extends IFly, ISwim{ } extends 继承
class Person implements IFly,ISwim { implements 实现
fly() {console.log('111')}
swim() {console.log('222’)}
}
3、类(class)
继承
A继承B A叫子类(派生类), B叫基类(超类)
多态
父类型的引用指向了子类型的对象,不同类型的对象针对相同的方法,产生了不同的行为
修饰符
public 共有的, private私有的,外部无法访问; protected 外部无法访问,子类可以访问
readonly修饰符
在外部无法修改,类中普通方法中不能修改,constructor中可以改
存取器
get () ; set() ; 可读可写
静态成员
static 静态属性或者方法
抽象类
abstract 抽象
不能实例化,子类中进行实例化和实现内部方法
4、函数
参数类型
可选参数:?可传可不传
默认参数:参数有默认值
剩余参数: ...args:string[] 剩余的参数放在数组里
函数重载 : 函数重载声明
5、泛型(<T>)
翻新参数
getArry1<T>(value: T, count: number): T[] { } 大写字母
getArry1<string>
多个泛型参数
getArry1<K,V>(value: K, count: V): [K,V] { }
泛型接口
interface IBaseCRUD<T> {
data: Array<T>
add: (t: T) => T
getUserId: (id: number) => T
}
泛型类
泛型约束
interface Ilength {
length: number
}
function getLength <T extends Ilength>(x: T):number {
return x.length
}