TS基础类型复习

72 阅读4分钟
  1. 联合类型

//如果是 基本类型 或字面量类型
//2.字面量联合类型
let string22: 'string1'|'string2'|'tome';

//3. 如果是对象类型
只能取他们的共有属性
interface Admin {
    name: string;
    age: number;
  }
  
  interface User {
    name: string;
    sayHi(): void;
  }
  declare function Employee(): Admin | User;
  Employee.name='s';
  Employee.age  =25 //类型“typeof Employee”上不存在属性“age”。


  1. 交叉类型
1 .//可以合并对象的属性和方法

type Person ={
    name: string;
}

type User2 ={
    age: number;
}

let person2:User2&Person;
person2 = {
    age:2,
    name:'23'
}
2.成员是基础类型
type T1= string&number;// type T1 = never;
//3. 成员类型合并
// 合并后的交叉类型将只保留一份该成员的类型。
type T2 = string & string & string;  // 等同于 type T2 = string
  1. 元组
有固定长度的数组,每一项的类型可以不同
通过[]定义
let temp :[number,string,undefined];
//元组是固定长度的数组
// let myTupe :[string,number]=[];// 需要给定长度
// let myTupe2 :[string,number]=[1,2];// 每一个类型都需要对应

// let myTupe3 :[string,number]=['1',2];
// myTupe3.pop();
// console.log(myTupe3.length);

  1. 枚举
 1. number会自动累加
enum num2{
    num11= 200,
    num22,
    num33= 300,
    num44,
}
console.log(num2.num11,num2.num22);//200, 201 会累加
2. //3.会报错,如果不是Number类型,不会自动累加
// enum num3{
//     num11= 'string',
//     num22,
// }

// console.log(num3.num11,num3.num22); 

//4. 可以使用计算值
const getValue:(a:number)=>number =(a=1)=>{
    return a;
}

enum num4 {
    num111=1,
    num222= getValue(2),
    // num333, //同样,如果使用了非Number不能累加
}

//5. 反向枚举
enum  reversNum5 {
    scc= 200,
    notFound= 404,
    err= 'string',
}

console.log(reversNum5[200],reversNum5['scc']);//scc 200
// console.log(reversNum5['string']);// 报错,---反向枚举仅支持number

//6.常量枚举
//仅仅为了可读性更好的话,可以用常量枚举  TypeScript 中有一个const enum(常量枚举),在定义枚举的语句之前加上const关键字,这样编译后的代码不会创建这个对象,只是会从枚举里拿到相应的值进行替换:
enum Status {
    Off,
    On
  }
  const enum Animal {
    Dog,
    Cat
  }
  const status2 = Status.On;
  const animal = Animal.Dog;





6.Known 未知,不能给已有类型的属性赋值

let e:unknown;
e= 'hello';

let y:string;
y = e; //报错,unknown 类型变量 不能直接赋值给其他变量

7.never

// never 永远不存在的值 
let ne: never;
// never 是所有类型的子类型
ne=123;//报错,never 永远不能给他赋值
//strictNullChecks false的情况下
let test2: string='1';
test2 = ne;


  1. 泛型

// 泛型
// 1. <>中使用
function same<T>(a:T):T {
    return a;
}
// 2.两个
type Fn =<T>(args:T)=>T;
const  myFunc2:Fn = function(args){
    return args;
}

interface Fn2<T>{
    (arg:T):T
}

const myFunc: Fn2<number> = function(a){
    return a+1
}


//3. 处理多个函数参数
// function swap(tuple) {
//     return [tuple[1], tuple[0]]
// }
function swap<T,U>(tuple:[T,U]): [U,T]{
    return[tuple[1],tuple[0]];
}


//4. 副作用操作
interface UserInfo {
    name: string
    age: number
}
// function request(url:string):Promise<UserInfo> {
//     return fetch(url).then(res => res.json())
// }
// request('user/info').then(res =>{
//     console.log(res)
// })
// 为每个接口设置不同的返回类型
function request<T>(url:string):Promise<T> {
    return fetch(url).then(res => res.json())
}
request<UserInfo>('user/info').then(res =>{
    console.log(res)
})
//5. 约束泛型

// function printLength<T>(arg: T): T {
//     console.log(arg.length) //没有length属性
//     return arg
// }
interface Mylength{
    length:number;
}
function myPrintLength<T extends Mylength>(arg:T):T{
    console.log(arg.length) //没有length属性
    return arg
}
//6. 泛型约束类
// 定义一个栈,有入栈和出栈两个方法
class Stack2<T>{
    private arr : T[]=[];

    push(item:T){
        return this.arr.push(item);
    }
    pop():T|undefined{
        return this.arr.pop();
    }
}
const s1 = new Stack2<number>()
// s1.pop('a')//报错类型必须是T
s1.push(1);// 可以
// 7. 泛型优化接口
interface MyInterface1<T,U>{
    key1: T,
    key2: U
}


const value1 :MyInterface1<number,string> ={
    key1: 1,
    key2:'s'
}
//8. 定义数组
const ar22: Array<number> = [1,2,3];

//9. 约束后端接口参数类型
interface API {
    '/book/detail': {
        id: number,
    },
    '/book/comment': {
        id: number
        comment: string
    }
    
}
function reque2st<T extends keyof API>(url:T,obj:API[T]): void {
    
}
reque2st('/book/comment', {
    id: 1,
    comment: '非常棒!'
})

[轻松拿下 TS 泛型 - 掘金 (juejin.cn)](https://juejin.cn/post/7064351631072526350?searchId=20240411213744C1B99C288275324203F1)

//Record \ readonly \ Pick


// 1. Record
// 以typeof格式,快速创建一个类型
type Coord = Record<'x'|'y',number>;
// 等同于
type Coord2 = {
    x: number,
    y: number
}
//2. Partial
// 将所有属性都修改成可选
type Coord3 = Partial<Record<'x'|'y',number>>; 
// type Coord3 = {
//     x?: number | undefined;
//     y?: number | undefined;
// }
//3. Readonly 只读

type Coord4 = Readonly<Record<'id'|'name',string>>;
// type Coord4 = {
//     readonly id: string;
//     readonly name: string;
// }

type CoordX = Pick<Coord, 'x'>;
// ===
// type CoordX = {
//     x: number;
// }

实现 pick readonly

// 实现 Pick
type Aprops ={
        name: string;
        value: number;
}
type Bprops = Pick<Aprops,'name'>;
// type Bprops = {
//     name: string;
// }
type MyPick<T, K extends keyof T>={
    [P in K]:T[P]
};

type Cprops = MyPick<Aprops,'value'>;
// type Cprops = {
//     value: number;
// }

// 实现 Readonly

type Dprops = Readonly<Aprops>;
type MyReadonly<T> = {
 readonly [P in keyof T]: T[P]
};
type Eprops = MyReadonly<Aprops>;

//