TS中语法学习

161 阅读2分钟

“我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第3篇文章,[点击查看活动详情] (s.juejin.cn/ds/jooSN7t "s.juejin.cn/ds/jooSN7t"…

TS中any与unknown的区别,原理,应用场景,存在意义

  1. 区别

    any表示任意类型,可以被任何类型分配,也可以分配给任何类型

     let randomValue: any = 10;
     randomValue = 'Mateo';   // OK
     randomValue = true;      // OK
    

    unkwon表示未知类型,可以被任何类型分配,不能分配给任何类型

    let bar: unknown = 222; // OK 
    console.log(bar.msg); // Error
    
    
    
  2. 使用场景

    any任何你想偷懒的场景,如果这样还不如用 js  unknown 使用 未知的或者不稳定的数据来源的数据结构。

3.联合类型中的 unkown

type UnionType1 = unknown | null;       // unknown
type UnionType2 = unknown | undefined;  // unknown
type UnionType3 = unknown | string;     // unknown
type UnionType4 = unknown | number[];   // unknown
type UnionType5 = unknown | any;  // any

4.交叉类型中的 unkown

type IntersectionType1 = unknown & null;       // null
type IntersectionType2 = unknown & undefined;  // undefined
type IntersectionType3 = unknown & string;     // string
type IntersectionType4 = unknown & number[];   // number[]
type IntersectionType5 = unknown & any;        // any

Record<string,unknown>调研

Record<K,T> 构造具有给定类型T的一组属性K的类型。在将一个类型的属性映射到另一个类型的属性时,Record非常方便。

interface EmployeeType {
    id: number
    fullname: string
    role: string
}
 
let employees: Record<number, EmployeeType> = {
    0: { id: 1, fullname: "John Doe", role: "Designer" },
    1: { id: 2, fullname: "Ibrahima Fall", role: "Developer" },
    2: { id: 3, fullname: "Sara Duckson", role: "Developer" },
}
 
// 0: { id: 1, fullname: "John Doe", role: "Designer" },
// 1: { id: 2, fullname: "Ibrahima Fall", role: "Developer" },
// 2: { id: 3, fullname: "Sara Duckson", role: "Developer" }

这里意思就是 数字作为类型,属性值的类型是EmployeeType,因此具有idfullNamerole字段的对象。

源码:

/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};

意思就是将K中的每个属性( [P in K] ),都转为T类型。常用的格式如下:

type proxyKType = Record<K,T>

会将K中的所有属性值都转换为T类型,并将返回的新类型返回给proxyKType,K可以是联合类型、对象、枚举…