深入理解typescript中的infer关键字的使用

作者:ESnail 时间:2023-10-13 19:19:33 

infer 这个关键字,整理记录一下,避免后面忘记了。有点难以理解呢。

infer

infer 是在 typescript 2.8中新增的关键字。

infer 可以在 extends 条件类型的字句中,在真实分支中引用此推断类型变量,推断待推断的类型。

例如:用infer推断函数的返回值类型


type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
type fn = () => number
type fnReturnType = ReturnType<fn> // number

在这个例子中,

T extends U ? X : Y的形式为条件类型。

infer R代表待推断的返回值类型,如果T是一个函数(...args: any[]) => infer R,则返回函数的返回值R,否则返回any

案例:加深理解

反解 Promise


// promise 响应类型
type PromiseResType<T> = T extends Promise<infer R> ? R : T
// 验证
async function strPromise() {
 return 'string promise'
}
interface Person {
 name: string;
 age: number;
}
async function personPromise() {
 return {
   name: 'p',
   age: 12
 } as Person
}
type StrPromise = ReturnType<typeof strPromise> // Promise<string>
// 反解
type StrPromiseRes = PromiseResType<StrPromise> // str
type PersonPromise = ReturnType<typeof personPromise> // Promise<Person>
// 反解
type PersonPromiseRes = PromiseResType<PersonPromise> // Person

反解函数入参类型


type Fn<A extends any[]> = (...args: A) => any
type FnArgs<T> = T extends Fn<infer A> ? A : any
function strFn (name: string) {
}
type StrFn = FnArgs<typeof strFn> // [string]

tuple 转 union ,如:[string, number] -> string | number


type ElementOf<T> = T extends Array<infer E> ? E : never
type TTuple = [string, number];
type ToUnion = ElementOf<ATuple>; // string | number

new 操作符


// 获取参数类型
type ConstructorParameters<T extends new (...args: any[]) => any> = T extends new (...args: infer P) => any ? P : never;
// 获取实例类型
type InstanceType<T extends new (...args: any[]) => any> = T extends new (...args: any[]) => infer R ? R : any;
class TestClass {
constructor(
   public name: string,
   public string: number
 ) {}
}
type Params = ConstructorParameters<typeof TestClass>;  // [string, numbder]
type Instance = InstanceType<typeof TestClass>;         // TestClass

react - reducer


// 定义
function useReducer<R extends Reducer<any, any>, I>(
 reducer: R,
 // ReducerState 推断类型
 initializerArg: I & ReducerState<R>,
 initializer: (arg: I & ReducerState<R>) => ReducerState<R>
): [ReducerState<R>, Dispatch<ReducerAction<R>>];
// infer推断
type ReducerState<R extends Reducer<any, any>> = R extends Reducer<infer S, any>
 ? S
 : never;
// Reducer类型
type Reducer<S, A> = (prevState: S, action: A) => S;
// 使用 reducer
const reducer = (x: number) => x + 1;
const [state, dispatch] = useReducer(reducer, '');
// Argument of type "" is not assignable to parameter of type 'number'.

vue3 - ref


export interface Ref<T = any> {
 [isRefSymbol]: true
 value: T
}
export function ref<T>(value: T): T extends Ref ? T : Ref<UnwrapRef<T>>
export type UnwrapRef<T> = {
 cRef: T extends ComputedRef<infer V> ? UnwrapRef<V> : T
 ref: T extends Ref<infer V> ? UnwrapRef<V> : T
 array: T
 object: { [K in keyof T]: UnwrapRef<T[K]> }
}[T extends ComputedRef<any>
 ? 'cRef'
 : T extends Array<any>
   ? 'array'
   : T extends Ref | Function | CollectionTypes | BaseTypes
     ? 'ref' // bail out on types that shouldn't be unwrapped
     : T extends object ? 'object' : 'ref']
// 使用
const count = ref({
 foo: ref('1'),
 bar: ref(2)
})
// 推断出
const count: Ref<{
 foo: string;
 bar: number;
}>
const count = ref(2) // Ref<number>
const count = ref(ref(2)) // Ref<number>

参考

理解TypeScript中的infer关键字

Vue3 跟着尤雨溪学 TypeScript 之 Ref 类型从零实现

巧用 TypeScript(五)---- infer

来源:https://www.cnblogs.com/EnSnail/p/14938799.html

标签:typescript,infer关键字
0
投稿

猜你喜欢

  • Python自定义函数实现求两个数最大公约数、最小公倍数示例

    2023-04-11 20:28:21
  • 用Python进行websocket接口测试

    2022-03-02 09:44:22
  • Python 点击指定位置验证码破解的实现代码

    2022-07-15 11:17:58
  • Python WSGI的深入理解

    2021-04-20 21:48:25
  • PHP获取url的函数代码

    2023-10-15 12:45:00
  • Python深入06——python的内存管理详解

    2021-07-29 05:18:26
  • Mysql事务操作失败如何解决

    2024-01-27 15:17:50
  • Golang使用Gin框架实现路由分类处理请求流程详解

    2024-05-29 22:07:41
  • python绘制评估优化算法性能的测试函数

    2022-10-18 20:13:20
  • Symfony2框架学习笔记之表单用法详解

    2023-11-14 17:51:48
  • python 字段拆分详解

    2021-03-16 22:59:58
  • python opencv 读取本地视频文件 修改ffmpeg的方法

    2023-10-13 09:10:38
  • python 查找文件名包含指定字符串的方法

    2021-05-03 08:54:21
  • Python终端输出彩色字符方法详解

    2023-11-18 22:04:17
  • linux下安装apache与php;Apache+PHP+MySQL配置攻略

    2023-11-14 15:43:46
  • Python中使用tkFileDialog实现文件选择、保存和路径选择

    2022-02-17 09:35:32
  • [MySQL binlog]mysql如何彻底解析Mixed日志格式的binlog

    2024-01-16 23:34:05
  • Python基于Faker假数据构造库

    2021-06-05 15:32:19
  • 用户体验量化方法研究(二)

    2010-02-08 12:46:00
  • vue+element-ui+sortable.js实现表格拖拽功能

    2024-04-09 11:00:11
  • asp之家 网络编程 m.aspxhome.com