学习笔记 Typescript | 青训营

96 阅读2分钟

TypeScript

和js对比

Why typescript?

超集 类型安全 提高效率

typescript的特性

  • TypeScript 是静态类型语言,通过类型注解提供编译时的静态类型检查

    • 在代码编译阶段会进行变量的类型检测,提前暴露潜在的类型错误问题。并且在代码执行阶段,不允许不同类型变量之间的赋值。
    • 清晰的类型注解,不仅让代码的可读性更好,同时也增强了 IDE 的能力,包括代码补全、接口提示、跳转到定义等等。
  • TypeScript 增加了模块类型,自带命名空间,方便了大型应用的模块化开发。

  • TypeScript 的设计一种完全面向对象的编程语言,具备模块、接口、类、类型注解等,可以让我们的代码组织结构更清晰。

typescript教程

awesome typescript

Typescript Playground

快速学习

TS基础

基本数据类型

boolean

number

string

undefined

null

any unkonwn void

never

array

tuple

代码实例

function test(x:string | number):boolean {   
    if(typeof x == 'string'){    
        return true;        }
    else if(typeof x == 'number'){  
            return false;   
    }   
    return throwError("Wrong Format");
}
function throwError(message:string):never{ 
    throw new Error(message); 
}

:指出了函数的返回值是boolean类型,并且还有异常处理 throwError,括号内的是输入类型,输入参数支持可选参数和默认参数,输出参数可由编译器推断,默认为void

function add(x: number[]):number//ts的函数重载 
function add(x:string[]):string 
function add(x:any[]):any{    
    if(typeof x[0]==='string')//注意有三个等号  
    {        return x.join();              
    }    if(typeof(x[0]=='number'))
    {       return x.reduce((acc,cur)==>acc+cur)  
                           }
                            }

ts-interface

类似于java,可以扩展,可选属性

interface Person{
    name:string
    age:number
}
interface RandomKey{
    [proName:String]:string
}
const obj:RandomKey={
    a:'Hello',
    b:'world',
    c:'typescript',
}
const p1:Person={
    name:'lin',
    age:18
}//实例化

冒号前面定义了变量,冒号后面定义了所属的类,obj继承了RandomKey类,并且用统一的方法写了属性a,b,c

ts-class

特点是有了public,private,protected等修饰符,而抽象类也有。还有约束类,使用implements关键字

class Person{
    protected name:string
    private sex:string
    public constructor(name:string){
        this.name = name
        this.sex = 'male'
    }
}
class Student extends Person{
    study(){
        console.log(this.name);
        
    }
}
let person = new Person("daming");

抽象类和C++类似,抽象类的所有属性都必须被继承。