深入理解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
0
投稿
猜你喜欢
- 当一张的数据达到几百万时,你查询一次所花的时间会变多,如果有联合查询的话,我想有可能会死在那儿了。分表的目的就在于此,减小数据库的负担,缩短
- 相信用过Gmail的人都知道Gmail有一个草稿自动保存的功能,每过一段时间,Gmail都会自动保存邮件草稿,这样在一些突 * 况下就能快速地
- 1.安装时选择的自动安装,忘了用户名和密码导致现在试了几个Oracle默认用户名密码後(表格中附带默认用户名及密码),都提示无效的用户名、密
- 1. TVP, 表变量,临时表,CTE 的区别 TVP和临时表都是可以索引的,总是存在tempdb中,会增加系统数据库开销,而表变量和CTE
- 我插入Mysql5的中文一直是乱码。但是直接使用mysqlAdmin,EMS等工具插入DB就不是乱码。而且我还可以使用程序正常地读出来。原因
- PyCharm 应该是大多数 python 开发者的首选 IDE,每天我们都在上面敲着熟悉的代码,写出一个又一个奇妙的功能。它是帮助用户在使
- 完成asp语言对XML文档中指定节点文本的增加、删除、修改、查看 <% '-------------------
- 1 为什么需要防抖和节流在前端开发当中,有些交互事件,会被频繁触发,这样会导致我们的页面渲染性能下降,如果频繁触发接口调用的话,会直接导致服
- IE 开发团队更改了 IE8 的 User-agent ,更改的部分信息如下:IE8 on Windows Vista (Compatibi
- “没 Javascript 就会死”的页面通常都会加入 noscript 标签用于提示用户开启脚本支持。 然而在 IE8 下,如果在 nos
- 什么是 Python 中的 Lambda 函数今天我们来学习 Python 中的 lambda 函数,并探讨使用它的优点和局限性Let
- 在windows下的解决办法如下: 1.net stop mysql 停用服务 &
- 内连接(inner join)。 外连接: 全连接(full join)、左连接(left join)、右连接(right join)。 交
- 在ASP中,除了ADODB、Scripting 等一些常用组件外,我们还可以用微软的ActiveX方法来轻松捕获哟: <%u
- 下载并选择MySQL的安装包由于MySQL一直在升级,所以当您阅读本文时,或许在其官方网站上已提供了新的正式版供你下载,因此,以下提供的链接
- 由于连续的字符(字母、符号、数字)在默认情况下是不换行的,可能会破坏整个界面布局。那如何解决这个问题呢?在 IE 和 Safari 1.3+
- 在使用 SQL Server 的过程中,用户遇到的最多的问题莫过于连接失败了。一般而言,有以下两种连接 SQL Server 的方式,一是利
- 1)用这个方法,把虚拟主机的默认页只设置成一个比如index.asp 在index.asp的最上面加入以下代码:<%if R
- 用HZHOST实用工具集的服务器安全设置里安装了MSSQL安全配置,现在SQL2000还原不了数据库了,从还原选定设备浏览文件夹时出现&qu
- XML.DOM需求有一个表,里面数据量比较大,每天一更新,其字段可以通过xml配置文件进行配置,即,可能每次建表的字段不一样。上游跑时会根据