深入理解typescript中的infer关键字的使用
作者:ESnail 发布时间:2023-10-13 19:19:33
标签:typescript,infer关键字
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


猜你喜欢
- 1概述 SQL语言的本质就是一串伪代码,表达的是做什么,而不是怎么做的意思。如其它语言一样,SQL语句需要编译之后才能运行,所以每一条SQL
- 本文研究的主要问题时Python读取word文本操作,分享了相关概念和实现代码,具体如下。一,docx模块Python可以利用python-
- 四年前写的一个内容管理系统,应用在公司内部网上,昨天DBA说其中的SQL语句未使用参数化的调用,导致服务器负担加重,资源占用大。并列出了几个
- PHP策略模式(Strategy Pattern)策略模式是一种行为设计模式,它允许在运行时选择算法行为的方法。该模式定义了一组算法,将每个
- 前言本文主要给大家介绍了关于mysql语句插入含单引号或反斜杠值的相关内容,下面话不多说了,来一起看看详细的介绍吧比如说有个表,它的结构是这
- 首先我们利用NodeJs先构建一个基本的服务器。 index.js var requestHandler = require(".
- 本文实例讲述了python实现同时给多个变量赋值的方法。分享给大家供大家参考。具体分析如下:python中可以同时给多个变量赋值,下面列举了
- 当使用MySQL做站点的时候,肯定会有不知道的错误发生,怎么记录呢?以下是具体解决方法:class.method //建立错误日志 func
- 代码如下:<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001&quo
- 对于大多数研发人员来说,都期望能找到一个良好的测试/调试方法,来提高工作效率和快速解决问题。所谓调试,偏重于对某个bug的查找、定位、修复;
- 没事在这里发一下关于数据库大批量插入数据的效率对比,用ACCESS和MSSQL,数值是在本机测试,根据不同的环境和配置,数值可能会有较大差别
- 随着大数据时代的到来,数据将如同煤电气油一样,成为我们最重要的能源之一,然而这种能源是可以源源不断产生、可再生的。而Python爬虫作为获取
- torch.Tensor类型的数据loss和acc打印时如果写成以下写法print('batch_loss: '+str(l
- 我们对 DataFrame 进行选择,大抵从这三个层次考虑:行列、区域、单元格。其对应使用的方法如下:一. 行,列 --> df[]二
- 我就废话不多说了,大家还是直接看代码吧!import kerasimport numpy as npfrom keras.applicati
- 新装MySQL后,首次执行 mysql -uroot -p 后会发现root密码不为空,要重置root密码请参考以下步骤。编辑mysql配置
- 一、php中pcntl_fork函数概述pcntl_fork()函数是php中用于创建子进程的一个函数,返回创建的子进程的pid。该函数创建
- 在python学习的过程中,我们最先接触到的就是python的数组,元组,字典等基础类型,但很少有人深入讨论python的内置序列类型以及它
- 如何利用SSH(Shell)来备份和恢复MySQL数据库的方法 例如: 数据库参数为:: MySQL地址:mysql.dh.net MySQ
- 最近做了一个微信小程序的项目,关于后端给我传递日期的时候,我拿到的是一串数字如:createDate: 1552117531000 ,这是一