#Ts篇:Pick&Omit&协变&逆变&Partial& interface 与 type 有何区别

Pick

Pick 接受两个类型参数,T 表示要从中选择属性的类型,K 表示选择的属性名的联合类型。通过映射类型,遍历联合类型 K 中的每个属性,然后从类型 T 中选择相应的属性。

type Pick<T, K extends keyof T> = {
  [P in K]: T[P];
};


interface Example {
  a: number;
  b: string;
  c: boolean;
}

type PickedType = Pick<Example, 'a' | 'b'>;
// PickedType 的类型为 { a: number, b: string }

Omit

我们使用了 Exclude 来排除 K 中的属性名,然后再通过 Pick 来选择剩余的属性。

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;




interface Example {
  a: number;
  b: string;
  c: boolean;
}

type OmittedType = Omit<Example, 'a' | 'b'>;
// OmittedType 的类型为 { c: boolean }

协变

let arr1: number[] = [1, 2, 3];
let arr2: (number | string)[] = arr1;
// 允许将 number[] 赋值给 (number | string)[]

逆变

type Printer<T> = (value: T) => void;

let numberPrinter: Printer<number> = (value: number) => {
  console.log(value);
};

let anyPrinter: Printer<any> = numberPrinter;
// 允许将 Printer<number> 赋值给 Printer<any>

Partial

在 TypeScript 中,Partial<T> 是一个内置的工具类型,它将类型 T 中的所有属性变为可选属性。

type MyPartial<T> = {
  [P in keyof T]?: T[P];
};
interface Example {
  a: number;
  b: string;
  c: boolean;
}

type PartialExample = MyPartial<Example>;
// PartialExample 的类型为 { a?: number, b?: string, c?: boolean }

interface 与 type 有何区别

共性:

都用于定义对象或函数的类型

区别:
  1. 声明使用的关键字不一样
  2. 合并性
  • interface具有合并特性
interface Car {
  brand: string;
  speed: number;
}

interface Car {
  model: string;
}

// 合并后的 Car 接口为 { brand: string; speed: number; model: string; }

  • type不具和并行,多次声名会导致冲突
type Car = {
  brand: string;
  speed: number;
};

type Car = {
  model: string;
};

// Error: 无法重新定义 "Car"

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值