• TypeScript 初识笔记


    目录

    一、基础静态类型和对象类型

    二、类型注解和类型推断

    三、元组的使用和类型约束

    四、接口

    五、类

    六、联合类型和类型保护

    七、枚举

    八、泛型

    九、tsconfig.json文件


    TypeScript 其实就是 JavaScript 的超集,也就是说 TypeScript 是建立在 JavaScript 之上的,最后都会转变成 JavaScript。TypeScript我也是一个初学者,在这里,我会简单总结一些关于TypeScript的特性,具体细节感兴趣者可参考中文官方文档

    TypeScript的主要特性如下:

    • 基础静态类型和对象类型
    • 类型注解和类型推断
    • 元组的使用和类型约束
    • 接口
    • 联合类型和类型保护
    • 枚举
    • 泛型
    • tsconfig.json文件

    一、基础静态类型和对象类型

    基础静态类型

    TypeScript最大的一个特点就是变量是强类型的,也就是说,在声明变量的时候,我们必须给他一个类型。常用的基础静态类型类型有:string、null、undefined 、Array、 boolean、 any 、void、 Tuple 、enum等

    1. const test1:string = "s"//字符串
    2. const test2:number = 1//数字
    3. const test3:null = null//null
    4. const test4:Array<number> =[1,2]//数组
    5. const test5:boolean = false//布尔
    6. const test6:any = 10//任意类型
    7. const test7:undefined = undefined//undefined

    对象类型

    对象类型大概可以分为四种

    • 对象类型
    • 数组类型
    • 类类型
    • 函数类型
    1. //对象类型--我们可以直接使用{propertyName:type,...}的形式来约束类型的名称和类型
    2. const ts:{name:string,age:number} = {name:"hello",age:22}
    3. //数组类型--基础静态类型的数组也可以为对象类型,这里就用string类型示例,其他类型数组都差不多
    4. const strArr:string[] =['a','b']
    5. //数组类型也可以这样表示
    6. const strArr:Array<string> = ['1','2']
    7. //类类型--需要自己先创建一个类,然后声明属性时约束其为创建的类
    8. class Class1{
    9. name:string;
    10. age:number
    11. }
    12. const class1:Class1 = {name:"a",age:12}
    13. const class2:Class1 = new Class1()
    14. //函数类型--声明变量为函数和返回值的类型
    15. const func:()=>string = ()=>"hello TypeScript"

    对象数组

    1. const man: { name: string, age: number }[] = [
    2. { name: "小A", age: 22 },
    3. { name: "小B", age: 22 },
    4. ]

    这种形式看起来比较麻烦,而且如果有同样类型的数组,写代码也比较麻烦,TypeScript 为我们准备了一个概念,叫做类型别名(type alias)。定义别名的时候要以type关键字开始。

    1. //type alias 类型别名
    2. type man = { name: string, age: number };
    3. //然后再定义数组的时候我们就可以用别名了
    4. const manArr: man[] = [
    5. { name: "小A", age: 22 },
    6. { name: "小B", age: 22 },
    7. ]

    还有我们如何控制一个数组中既有数字或者有字符串呢, 很简单,只要加个(),然后在里边加上|就可以了,具体如代码所示。

    const arr3: (number | string)[] = [1, "2", 3];

    二、类型注解和类型推断

    类型注解即我们声明变量时指明了变量的类型,这就变量注解。

    let count1:number;

    TypeScript里,在有些没有明确指出类型的地方,类型推论会帮助提供类型。

    const x = 2;

    变量x的类型被推断为数字。这种推断发生在初始化变量和成员,设置默认参数值和决定函数返回值时。

    三、元组的使用和类型约束

    元组和数组类似,但是类型注解时会不一样,元组是对数组中的每一个元素都确定了类型。其实你可以把元组看成数组的一个加强,它可以更好的控制或者说规范里边的类型。

    1. //元组
    2. const xiaoge: [string, string, number] = ['a', 'b', 28];
    3. //元组数组
    4. const xiaoge: [string, string, number][] = [['a', 'b', 28],['a1', 'b1', 28],['a2', 'b2', 28]]

    四、接口

    接口声明示例:如下代码所示,我们可以在接口中指定属性的类型,属性名?代表当前属性为可选字段(可以赋值,也可以不赋值)

    [propname:string]:any 用于新增一些任意属性,属性的名字是字符串类型,属性的值可以是任何类型。

    1. interface Person {
    2. name: string;
    3. age: number;
    4. height?: number;
    5. [propname:string]:any;//any为任意类型
    6. say():string//可声明函数
    7. }

    接口和接口之间可以继承,使用关键字extends,子接口将拥有父级接口的所有属性和函数

    1. interface Student extends Person{
    2. studentNo:string
    3. }
    4. //使用接口进行注解,被注解的变量需要对接口中所有不是可选属性的属性进行赋值,不然代码就会提示错误
    5. const stu:Student = {name:"小A",age:20,studentNo:"A01",say() {
    6. return "我是小A"
    7. },}

    使用类实现接口,实现需要用到关键字implements,也需要对接口中所有不是可选属性的属性进行赋值,函数也必须实现,不然代码就会提示错误

    1. class StuB implements Student{
    2. name = "小B"
    3. age = 22
    4. studentNo = "B01"
    5. say(){return "hello"}
    6. }

    五、类

    TypeScript类主要内容有:

    • 类的基本使用
    • 类的继承、重写和super关键字
    • 类的访问类型
    • 类的构造函数
    • 类的Getter、Setter、Static和只读属性
    • 抽象类

    类的基本使用

    就像这样,可以声明一些变量和方法,使用类时可以通过new关键字生成对象

    1. class Animal{
    2. content = "动物";
    3. say(){
    4. return this.content
    5. }
    6. }
    7. const animal:Animal = new Animal()

    类的继承、重写和super关键字

    继承:使用extends关键字,子类将拥有父类的所有属性和方法,当然也可以自己的属性和方法

    1. class Bird extends Animal{
    2. fly(){
    3. return "I can fly"
    4. }
    5. }
    6. const bird:Bird = new Bird();
    7. console.log(bird.say())//动物
    8. console.log(bird.fly())//I can fly

    重写:类的重写主要是子类对父类函数的重写,就是父类有一个函数,子类定义一个与父类同名同参的函数,然后这个函数可以与父类有不一样的实现。

    1. //Animal类也是有say()函数的,这里子类再次定义say()函数就是对父类函数的重写
    2. class Bird extends Animal{
    3. say(){
    4. return "I am a bird"
    5. };
    6. fly(){
    7. return "I can fly"
    8. }
    9. }

    super关键字:用于子类调用父类的属性和方法

    1. class Bird extends Animal{
    2. say(){
    3. return super.content+ "-- bird"//调用父类函数就可以用super.say()
    4. };
    5. fly(){
    6. return "I can fly"
    7. }
    8. }

    类的访问类型

    类的访问类型只有三种public、private、protected

    • public -- 代表类的内部和外部对可以使用
    • private -- 代表只允许内的内部调用,子类也无法使用
    • protected -- 代表类内部和其子类可以使用,内的外部无法使用
    1. //public
    2. class Person {
    3. public name = "person";
    4. public sayHello() {
    5. console.log(this.name + " hello");
    6. }
    7. }
    8. const person = new Person()
    9. console.log(person.name);//person(因为是public,所以外部能访问到Person.name)
    10. person.sayHello();//person hello
    11. //private,它的子类访问不到name属性
    12. class Person2 {
    13. private name = "person";
    14. public sayHello() {
    15. console.log(this.name + " hello");
    16. }
    17. }
    18. const person2 = new Person2()
    19. //console.log(person2.name);编译不通过Property 'name' is private and only accessible within class 'Person2'.
    20. person2.sayHello();//person hello
    21. //protected,它的子类可以访问到name属性
    22. class Person3 {
    23. protected name = "person";
    24. public sayHello() {
    25. console.log(this.name + " hello");
    26. }
    27. }
    28. const person3:Person3 = new Person3()
    29. //console.log(person3.name);编译不通过:Property 'name' is protected and only accessible within class 'Person3' and its subclasses.
    30. person3.sayHello();//person hello

    类的构造函数

    类构造函数的基本使用,使用constructor函数

    1. class TestA{
    2. public name:string;
    3. constructor(name:string){
    4. this.name = name
    5. }
    6. }
    7. //可以简写为
    8. class TestA{
    9. constructor(public name:string){
    10. this.name = name
    11. }
    12. }
    13. const t1:TestA = new TestA("小A");
    14. console.log(t1.name);//小A

    子类继承父类后构造函数中必须使用super调用父类的构造函数

    1. //继承的构造函数
    2. class TestB extends TestA{
    3. constructor(public age:number){
    4. //在子类的构造函数中必须写super(),若不写会报错
    5. super('小B')
    6. this.age = age;
    7. }
    8. }
    9. const testB:TestB = new TestB(23)
    10. console.log(testB.name);//小B
    11. console.log(testB.age);//23

    类的Getter、Setter和Static

    当变量被声明为私有变量时,无法直接访问到属性值,这里就可以通过设置get和set函数来取值赋值,使用时就和获取public变量一样了。

    1. class GSClass{
    2. constructor(private _age:number){}
    3. get age(){
    4. return this._age
    5. }
    6. set age(age:number){
    7. this._age = age
    8. }
    9. }
    10. const gs = new GSClass(23);
    11. gs.age = 24;
    12. console.log(gs.age);

     static用于不需要实例化对象就可以调用类的方法

    1. class Boy{
    2. static sayLove(){
    3. return "I Love You"
    4. }
    5. }
    6. console.log(Boy.sayLove());

    只读属性

    使用readonly关键字进行修饰,顾名思义,只读属性只用于数据读取,不能进行赋值

    1. class Server{
    2. public readonly _name:string;
    3. constructor(name:string){
    4. this._name = name
    5. }
    6. }
    7. const user = new Server("rr")
    8. console.log(user._name);

    抽象类

    使用abstract关键字修饰的类为抽象类

    抽象类中可以声明抽象函数(也可以有普通函数),也是用abstract关键字修饰

    子类继承抽象类必须实现抽象类中所有抽象方法

    1. //抽象类
    2. abstract class A{
    3. abstract skill();
    4. }
    5. class B extends A{
    6. skill() {
    7. console.log("s1");
    8. }
    9. }

    六、联合类型和类型保护

    1. interface Waiter {
    2. anjiao: boolean;
    3. say: () => {}
    4. }
    5. interface Teacher {
    6. anjiao: boolean;
    7. skill: () => {}
    8. }
    9. //
    10. function judgeWho(person: Waiter | Teacher) {
    11. //断言
    12. if (person.anjiao) {
    13. (person as Teacher).skill();
    14. } else {
    15. (person as Waiter).say();
    16. }
    17. }
    18. function judegeWhoTwo(person: Waiter | Teacher) {
    19. if ("skill" in person) {
    20. person.skill();
    21. } else {
    22. person.say();
    23. }
    24. }
    25. function add(first: string | number, second: string | number) {
    26. if (typeof first === "string" || typeof second === "string") {
    27. return `${first}${second}`
    28. }
    29. return first + second
    30. }
    31. class NumberObj{
    32. count:number;
    33. }
    34. //instanceof 只能用在类上
    35. function addObj(first: object| NumberObj,second:object| NumberObj){
    36. if(first instanceof NumberObj && second instanceof NumberObj){
    37. return first.count + second.count
    38. }
    39. return 0;
    40. }

    七、枚举

    1. //默认值从0开始
    2. enum Status {MESSAGE,SPA,DABAOJIAN}
    3. //这样枚举就从1开始了
    4. //enum Status {MESSAGE = 1,SPA,DABAOJIAN}
    5. function getServe(status:number){
    6. if(status === Status.MESSAGE){
    7. return "message"
    8. }else if (status === Status.SPA){
    9. return "spa"
    10. }else if (status === Status.DABAOJIAN){
    11. return "dajiao"
    12. }
    13. }const result = getServe(Status.MESSAGE);
    14. // const result = getServe(0);
    15. console.log(result);
    16. ///这样输出为数字 0 , 1 ,2
    17. console.log(Status.MESSAGE);//0
    18. console.log(Status.SPA);//1
    19. console.log(Status.DABAOJIAN);//2
    20. //反查 (其实数字代表的是具体枚举代表的值)
    21. console.log(Status[0]);//MESSAGE
    22. console.log(Status[1]);//SPA
    23. console.log(Status[2]);//DABAOJIAN

    八、泛型

    函数上泛型的使用

    1. function join(first:string|number ,second:string|number){
    2. return `${first}${second}`
    3. }
    4. join("ss","com")
    5. //保证first和second的类型一致
    6. function join2(first:T ,second:T){
    7. return `${first}${second}`
    8. }
    9. join("ss","com")
    10. join2<number>(1,2);
    11. //数组
    12. function myFunc(params:Array){
    13. return params;
    14. }
    15. myFunc<string>(["123","456"]);
    16. //多种类型
    17. function myFunc2(first:T,second:P){
    18. return `${first}${second}`
    19. }
    20. myFunc2<string,number>("2",1);

    类上泛型的使用

    1. interface TT{
    2. name:string
    3. }
    4. class SelectGirlextends TT>{
    5. constructor(private girls:T[]){}
    6. getGirl(index:number):string{
    7. return this.girls[index].name;
    8. }
    9. }
    10. const selectGirl = new SelectGirl([{name:"小A"} ,{name:"小B"},{name:"小C"}]);
    11. console.log(selectGirl.getGirl(1));

    九、tsconfig.json文件


    相关链接:编译选项 · TypeScript中文网 · TypeScript——JavaScript的超集

  • 相关阅读:
    JUC三大常用工具类CountDownLatch、CyclicBarrier、Semaphore
    Ansible 自动化运维企业实战(一)
    李永乐线代笔记
    git 设置ignore文件
    安装 Windows Server 2019 VM虚拟机
    R语言学习笔记——入门篇:第四章-基本数据管理
    docker命令介绍,镜像制作,容器启动,进入容器操作等
    09 # 手写 some 方法
    采煤vr事故灾害应急模拟救援训练降低生命财产损失
    跨语言指令调优深度探索
  • 原文地址:https://blog.csdn.net/chaseqrr/article/details/126473623