ts的重载

本文介绍了TypeScript中的高级类型特性,如TemplateLiteralTypes、typeExclude、Exclude、infer等,展示了如何使用这些工具来处理接口类型、函数参数类型以及数组和Promise类型的提取。
摘要由CSDN通过智能技术生成

官网示例 TypeScript: Documentation - Template Literal Types

这里大概理解是 T 继承了Number|sting 

加上?条件判断就是 T继承Number|sting 部分为true 没有继承部分为false,

就是输入string, 为true, 输入 null 则为false,

type Exclude<T, U> = T extends U ? never : T;

// 相当于: type A = 'a'

type A = Exclude<'x' | 'a', 'x' | 'y' | 'z'>

输入x 此时为true 返回never, 输入a 返回a 

此处就变成了 返回不包含在U集合的类型

 // 如何得到 'c' | 'd' ?

interface SomeProps { a: string b: number c: (e: MouseEvent) => void d: (e: TouchEvent) => void } // 如何得到 'c' | 'd' ?
type GetKeyByValueType<T, Condition> = {
    [K in keyof T]: T[K] extends Condition ? K : never
} [keyof T];

type FunctionPropNames =  GetKeyByValueType<SomeProps, Function>;    // 'c' | 'd'

等同于
type ExType<T> = {
  [k in keyof T]: T[k] extends  (e: infer E) => void? k : never
}[keyof T]
// 开始
{
    a: string
    b: number
    c: (e: MouseEvent) => void
    d: (e: TouchEvent) => void
}
// 第一步,条件映射
{
    a: never
    b: never
    c: 'c'
    d: 'd'
}
// 第二步,索引取值
never | never | 'c' | 'd'
// never的性质
'c' | 'd'

 
type Concrete<Type> = {
  [Property in keyof Type]-?: Type[Property];
};
 
type MaybeUser = {
  id: string;
  name?: string;
  age?: number;
};
 
type User = Concrete<MaybeUser>;
      
type User = {
    id: string;
    name: string;
    age: number;
}

-可以删除? 和readonly

解释一下infer

infer 关键字用于 TypeScript 中的条件类型。在这种情况下, infer 关键字用于提取函数类型的参数类型。具体来说, SomeProps[k] extends (e: infer E) => void ? E : never 这段代码的作用是,如果 SomeProps[k] 是一个函数类型,那么就提取该函数类型的参数类型作为 E ,否则返回 never 。 
 
换句话说,当 SomeProps 对象中的属性值是函数类型时,通过 infer 关键字提取函数类型的参数类型,并将其赋值给 E 。这样,就可以在 TypeScript 的类型系统中使用这个参数类型进行进一步的操作或推断。 
 
 

[k in keyof SomeProps]: SomeProps[k] extends (e: infer E) => void ? E : never 
type ExtractMemberType<T> = T extends (infer U)[] ? U : never;

type Fruit = "Apple" | "Banana" | "Orange";
type FruitArray = Array<Fruit>;

type FruitType = ExtractMemberType<FruitArray>; // Fruit
type ExtractPromiseType<T> = T extends Promise<infer U> ? U : never;

type PromiseString = Promise<string>;

type StringType = ExtractPromiseType<PromiseString>;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值