typeScript学习笔记(一): 基础使用

78 阅读3分钟

一、下载安装

npm

npm install typescript --save-dev

yarn

yarn add typescript --dev

pnpm

pnpm add typescript -D

二、语法

ts语法中可以声明变量类型,如果数据与声明的变量类型不一致时,会报出异常; 没有声明变量类型时,默认是any泛型。

1、声明变量

// javascript语法声明变量
let param = "string";

// ts声明变量
let param: string = "测试"; 
let param: string = "123";
let param: string = 123; // 报错 

2、声明函数

// js语法声明函数
function func() {
   ... ...
}

// ts声明函数
// 函数参数指定数据类型
function func(param: string) {
    ... ...
}
// 函数参数指定返回的类型
function func(): string {
   return 'string';
}
// 推断
function func<Type>(param: Type): Type {}

3、类
1) 基础使用

class className {
    // 成员
    id: number;
    name: string;
    
    // 构造函数,可定义参数和不定义参数
    construcror() {
        super();
    }
}

2) 继承

class base {
    id: number;
}

class student extends base {
    name: string;
    year: number;

    // 构造函数
    constructor(id:number, name: string, year: number) {
        super();
        this.id = id;
        this.name = name;
        this.year = year;
    }

    getStudy() {
        return this.id + '、' + this.name + '今年' + this.year + "岁";
    }

}

let studys = new study(2, '张三', 18);
console.log(studys.getStudy());

3)覆盖

class base {
    id: number;
    getStudent() {
        return 'get student';
    }
}

class student extends base {
    name: string;
    year: number;

    constructor(id: number, name: string, year: number) {
        super();
        this.id = id;
        this.name = name;
        this.year = year;
    }

    getStudent() {
        return this.id + '、' + this.name + '今年' + this.year + '岁';
    }
}

const students = new student(2, '张三', 22);
console.log(students.getStudent());

4)可见性
① public 默认
② protected 内部及派生类可使用

class base {
    protected id: number;
    getStudent() {
        return 'get student';
    }
}

class student extends base {
    name: string;
    year: number;

    constructor(id: number, name: string, year: number) {
        super();
        this.id = id;
        this.name = name;
        this.year = year;
    }

    getStudent() {
        return this.id + '、' + this.name + '今年' + this.year + '岁';
    }
}

const students = new student(3, '张三', 22);

③ private 仅内部类可以使用

class base {
    private id: number;
    getStudent() {
        return 'get student';
    }
}

class student extends base {
    name: string;
    year: number;

    constructor(id: number, name: string, year: number) {
        super();
        this.id = id; // ts允许在派生类中使用
        this.name = name;
        this.year = year;
    }

    getStudent() {
        return this.id + '、' + this.name + '今年' + this.year + '岁';
    }
}

5)静态

class base {
    static id = 1;
}

class numberId extends base {
    new_id = numberId.id;
}

let model = new numberId();
console.log(model.new_id);
</script>

三、类型

1、基础类型: string、number、boolean

let data: string = "string";
let data: number = 123;
let data: boolean = true;

2、array

let data: string[] = ['aaa', 'bbb'];
let data: number[] = [1111, 2222];

3、对象类型

let data: {name: string, id: number} = {
    id: 12,
    name: "张三"
}

4、函数function

function func(func: void) {}

5、联合类型

let data: string | number = 123;
let data: (string | number)[] = ['aaa', 123]

6、接口

interface face {
    name: string;
}

function func(param: face) {
    return param['name'];
}

console.log(func({name: 'aaaa'}));

7、字面类型

let data: 'A' = 'A';
let data: 'B' = 'B';
let data: 1 = 1;
let data: 2 = 2;
let data: true = true;
let data: false = false;

8、null和undefined

function func(param: string | null | undefined) {}

9、枚举
10、bigint、symbol等不常见

四、类型操作

1、泛型

// 基础款
function func(param: any): any { }

// 类型捕获,类型推断
function func<Type>(param: Type): Type {}
func<string>('123');
func<number>(123);

// 类型变量
function identity<Type>(arg: Array<Type>): Array<Type> {
    return arg;
}

// 泛型类型
function func<Type>(param: Type): Type {
    return param;
}

let data: <Type>(param: Type) => Type = func;
console.log(data<string>('泛型类型'));

// 泛型类, 感觉泛型类并没有什么实际的作用
class myClass<string> {
    id: number = 12;
    getString<string>(): string {
        return "sdddaa";
    }

    getNumber<number>():number {
        return 123444;
    }
}

let cl = new myClass<string>();
console.log(cl.getString());
console.log(cl.getNumber());
console.log(cl.id);

// 泛型默认值
function func(id: number = 2) {}

2、keyof

type point = { x: number, y: number}
type p = keyof point;

3、typeof

type point = { x: number, y: number}
type p = typeof point;

4、索引访问

type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"];

5、条件类型

interface Animal {
    live(): void;
}
interface Dog extends Animal {
    woof(): void;
}

type Example1 = Dog extends Animal ? number : string;

type Example2 = RegExp extends Animal ? number : string;

6、映射类型

type OnlyBoolsAndHorses = {
  [key: string]: boolean | Horse;
};
 
const conforms: OnlyBoolsAndHorses = {
  del: true,
  rodney: false,
};

// 通过keyof
type OptionsFlags<Type> = {
  [Property in keyof Type]: boolean;
};

// 映射修饰符
// 在映射期间可以应用两个额外的修饰符:`readonly` 和 `?` 分别影响可变性和可选性。
// 你可以通过添加前缀 `-` 或 `+` 来移除或添加这些修饰符。如果你不添加前缀,则假定为 `+`。
type CreateMutable<Type> = {
  -readonly [Property in keyof Type]: Type[Property];
};
 
type LockedAccount = {
  readonly id: string;
  readonly name: string;
};
 
type UnlockedAccount = CreateMutable<LockedAccount>;

// 通过 `as` 重新映射键
type Getters<Type> = {
    [Property in keyof Type as `get${Capitalize<string & Property>}`]: () => Type[Property]
};
 
interface Person {
    name: string;
    age: number;
    location: string;
}
 
type LazyPerson = Getters<Person>;

// 通过条件类型生成 `never` 来过滤掉键
type RemoveKindField<Type> = {
    [Property in keyof Type as Exclude<Property, "kind">]: Type[Property]
};
 
interface Circle {
    kind: "circle";
    radius: number;
}
 
type KindlessCircle = RemoveKindField<Circle>;

7、模板字面类型

type World = "world";
 
type Greeting = `hello ${World}`;

// 字符串字面的集合
type EmailLocaleIDs = "welcome_email" | "email_heading";
type FooterLocaleIDs = "footer_title" | "footer_sendoff";
 
type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;

// 联合是交叉相乘
type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;
type Lang = "en" | "ja" | "pt";
 
type LocaleMessageIDs = `${Lang}_${AllLocaleIDs}`;