Typescript简介
相较于类型松散的JS的不同,Typescript 是一门静态类型语言,在编译期间做类型检查。因此,Ts在使用的时候,就没那么方便,并且学习成本也更高一些。但在大型项目里,就能够彰显ts的优势了,前期对各种数据进行类型的定义,后期就不容易出错。
原始数据类型
booeal,string,number,undefined,null,any。
any: 如果给变量指定该数据类型,那么这个变量可以是任意类型
let isDone: boolean = false
let age: number = 20
let firstName: string = 'zebra'
let message: string = `hello,${firstName}`
let u: undefined = undefined
let n: null = null
数组、元组(tuple)
数组:跟js有一些不同,ts可以指定数组里的元素的类型
元组:限制数组里元素的类型为某几种(口头描述还是不准确),官方文档的表述是:
元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同。
用代码说话更清晰易懂:
let arrOfNumbers: number[] = [1,2,3,4] // arrOfNumbers里的元素只能为number,否则编译器会报错
let arrOfStr: Array<String> = ['a', 'b']
let user: [string, number] = ['zebra', 1234] // 第一个数必须是字符串,第二个必须是number类型
user.push('1234') // 使用push方法的时候,既可以是string,也可以是number
接口(interface)
对对象形状(shape)进行描述
Duck Typeing (鸭子类型,顾名思义:只要长得像鸭子,叫起来像鸭子就算是鸭子类型)
interface person {
id: number,
name: string,
age?: number
}
let zebra: person = {
id: 1,
name: 'zebra',
age: 20 // 可选项,该属性可有也可以没有,但是其他属性不可以没有,否则编译器会报错。
}
console.log(zebra.name) //'zebra'
函数function
// 函数具有输入输出,也有类型
// add函数的类型就是 (x: number, y: number, z?: number) : number
const add = (x: number, y: number, z?: number) : number=> {
if(typeof z === 'number') {
return x + y + z
}else {
return x + y
}
}
// 使用接口定义函数的类型
interface ISum {
(x: number, y: number, z?: number) : number
}
const add2: ISum = add
类型推断(type inference):在没有明确指定变量的数据类型时,编译器会自动推断它的类型
let str = 'abc' // str自动获取string类型
联合类型(union types): 一个变量可以为多种数据类型中的一种
let stringOrNumber: string | number // 在未被赋初始值之前该变量只能访问联合类型公共的方法
类型断言: 当你清楚得知道一个实体具有更为详细的数据类型时,告诉编译器,“相信我,我知道自己在干什么”,这时,编译器就不进行数据类型的检查
function getLength(input: string | number): number{
if(input.length) {
const str = input as string
return str.length
}else {
const num = input as number
return num.toString().length
}
}
类型守卫(type guard):在进行类型判断的时候,会自动得到类型。
function getLength1(input: number | string): number{
if(typeof input === 'string') {
return input.length
}else { // 这一个分支里,input自动被断定为number类型
return input.toString().length
}
}
类:ts中的类可以被三类修饰符给修饰
public: 修饰的属性或者方法是共有的
private: 修饰的属性或者方法是私有的
protected: 修饰的属性或者方法是受保护的
类和接口的使用: 类可以被继承,接口也可以被继承
// 类和接口的使用
interface Battery {
checkBatteryStatus(trigger: boolean): void;
}
interface Radio {
switchRadio(): void;
}
// 接口之间也可以继承
interface BatteryAndRadio extends Battery{
switchRadio(): void;
}
class Car implements Battery{
checkBatteryStatus(trigger: boolean) {
}
}
class CellPhone implements BatteryAndRadio{
checkBatteryStatus(trigger: boolean) {
}
switchRadio() {
}
}
泛型:使用<>来占位,不在初始化时就给数据类型,而是在使用时,动态填入类型值
function echo<T>(arg: T): T {
return arg
}
const result = echo('str') //result类型就是string
function swap<T, U>(tuple: [T, U]): [U, T] {
return [tuple[1], tuple[0]]
}
const res = swap([1,'123'])