type MyPick<T, K extends keyof T> = {
[P in K]: T[P]
}
让interface中所有属性变为可读
type MyReadonly<T> = {
readonly [K in keyof T]: T[K]
}
将元组类型转换为对象类型
type tupleToObject<T extends any[]> ={
[k in T[number]]: k
}
type First<T extends any[]> = T extends []? never: T[0]
T["length"] extends 0 ? never : T[0]
T[0] extends T[number]? never: T[0]
T extends [ infer First, ...infer Rest]? First : never
type MyExclude<T,U> = T extends U? never:T
type includes<T extends readonly any[], U> = T extends [infer First, ...infer Rest] ? Equal<First,U> extends true ? true : inlcudes<Rest, U> : false
type MyReturnType<T> = T extends (...args:any) => infer R ? R : never
//例子
{
name: '123',
age: {
same: true
}
}
type Chainable<T = {}> = {
option: <K extends string, V>(key: K extends T ? V extends T[K]? never : K : K, value: V) => Chainable<Omit<T,K> & Record<K, V>>
get: () => T
}
type Last<T extends any[]> = T extends [...infer Rest, infer L] ? L : never
type Space = ' ' | '\n' | '\t'
type TrimLeft<S extends string> = S extends `${Space}${infer R}` ? TrimLeft<R> : S
type Capitalize<S extends string> = S extends `${infer x}${infer Rest}` ? `${UpperCase<X>}${Rest}` : S
type Replace<S extends string, From extends string, To extends string> = From extends ''? S : S extends `${infer V}${From}${infer R}` ? `${V}${To}${R}` : S
type AppendArguments<Fn,A> = Fn extends (...args: infer R) => infer T ? (...args:[...R, A]) => T : never
type Permutation<T,K=T> = [T] extends [never] ? [] : K extends K ? [K, ...Permutation<Exclude<T,K>>] : never
type LengthOfString<S extends string, T extends string[] = []> = S extends `${infer L}${infer R}` ? LengthOfString<R,[...T,R]> : T['length']
type Flatten<T extends any[], U extends any[] = []> = T extends [infer L, ...infer Rest] ? L extends any[] ? Flatten<[...L,...Rest],U> : Flatten<[...Rest],[...U,L]> : U
需要限定key的范围,对象的键名应为字符串或数字
type AddToObject<T,U extends keyof any,V> = {
[K in keyof T | U] : K extends keyof T? T[K]:V
}