TS类型体操

33 阅读1分钟

//KebabCaseToCamelCase
//K guang-and-dong 转换成 guangAndDong。

type transferString<T extends String> = T extends `${infer item}-${infer rest}` ? 
`${item}${transferString<Capitalize<rest>>}`:T

type test = transferString<'guang-and-dong'>
// 根据数组类型,比如 [‘a’, ‘b’, ‘c’] 的元组类型,再加上值的类型 'xxx',构造出这样的索引类型:

// {
//     a: {
//         b: {
//             c: 'xxx'
//         }
//     }
// }


// 对象类类型,键不能是null,as 是作为重映射改变键 key of any 取出当前索引支持那些类型
type arrTransfer<T extends unknown[],V> =  T extends [infer first,  ...infer rest] ? {
	[key in first as key  extends keyof any?  key : never]: rest extends unknown[] ? arrTransfer<rest,V> : V
} : V

type test2 = arrTransfer<['a','b',undefined],3>


// PartialObjectPropByKeys

type Copy<Obj extends Record<string, any>> = {
    [Key in keyof Obj]:Obj[Key]
}
// 这里还加了一个重新构造索引类型, 默认为何不会计算类型呢???
type PartialObjectPropByKeys<T extends Record<string,any>,P extends keyof any> =
 Copy<Partial<Pick<T,keyof T&P>> &Omit<T,P>>
interface Dong {
    name: string
    age: number
    address: string
}
type test3 = PartialObjectPropByKeys<Dong,'name'| 'age'| 'commonAncestorContainer' >


// 子类型,想去赋值给父类那就属于 , 协变, 父类赋值给子类属于逆变,这个函数调用的时候用
function join (str:string){
	return (...args:any)=>{
		console.log(args)
	}
}
// 函数类型定义,一定要泛型吗,是为了能在调用的时候,去复用类型定义,避免写死,但是为什么不直接写到函数参数里面呢
// 泛型的约束为什么,不直接去用声明具体类型,非得用extends 

const res = join('-')('guang', 'and', 'dong');

// type joinReturnType<T extends string>= (...args:unknown[])=> [infer first,...rest: unknown[]]  

declare function join<T extends string>(t:T) : <Items extends string[]>(...ars:Items) => JoinType<Items,T>

//里面的 [infer item,...args:Items] extends Items  这个为什么不能颠倒呢
type JoinType<Items extends string[],T extends string,result extends string=''>= [infer item,...args:Items] extends Items 
? JoinType<args,T,`${result}${item}${T}`>:





字节面试题

image.png

type parate = '-' | '.' | '/'
type FormateDate<T extends string> =  T extends `${infer Day}${parate}${infer Month}${parate}${infer Year}` ? `${GenStr<Day>}${parate}${GenStr<Month>}${parate}${GenStr<Year>}`:never;

type   Dates =   0 | 1| 2 | 3| 4|5 |6|7|8 |9;
type res = FormateDate<'11-22-2024'>;
const ass: FormateDate<'DD-MM-YY'> ='11-12-2024';
type DayType = `${Dates}${Dates}`
type MonthType = `${Dates}${Dates}`
// type YearType = `${Dates}${Dates}${Dates}${Dates}`

type DayType1 = `${0 | 1 | 2 |3}${Dates}`
type MonthType1 = `${0|1}${Dates}`;
type YearType = `20${Dates}${Dates}`


type GenStr<Type extends string> = 
  Type extends 'YY'
    ? YearType
    : Type extends 'MM'
      ? MonthType1
      : DayType1;