31. 计算字符串长度
// 计算字符串的长度,类似于 String#length 。
答案
type test = Str1<"abc123">;
type Str1<T extends string, L extends any[] = []> = T extends `${infer f}${infer b}` ? Str1<b, [...L, f]> : L['length'];
32. 接口添加字段
// 实现一个为接口添加一个新字段的类型。该类型接收三个参数,返回带有新字段的接口类型。例如:type Test = { id: '1' }
type Result = AppendToObject<Test, 'value', 4> // expected to be { id: '1', value: 4 }
答案
type AppendToObject<T, K extends string, N,> = {[P in (keyof T | K)]: P extends keyof T ? T[P] : N
}
33.返回一个正数字符串
Absolute
实现一个接收string,number或bigInt类型参数的Absolute类型,返回一个正数字符串。例如
type Test = -100;
type Result = Absolute<'-12309'>; // expected to be "100"
答案
type Absolute<T> = T extends (string|number|bigint) ? `${T}` extends `${'-'}${infer F}` ? F: `${T}` :''
34. 字符串转字母联合类型
String to Union
实现一个将接收到的String参数转换为一个字母Union的类型。例如
type Test = '123';
type Result = StringToUnion<Test>; // expected to be "1" | "2" | "3"
答案
type StringToUnion<T, F extends any[] = []> =
T extends `${infer First}${infer O}` ? StringToUnion<O, [ ...F, First]> : F[number]
35. merge合并两个接口类型
// Merge
// 将两个类型合并成一个类型,第二个类型的键会覆盖第一个类型的键。// 例如
type foo = {name: string;age: string;}type coo = {age: number;sex: string}type Result = Merge<foo,coo>; // expected to be {name: string, age: number, sex: string}
答案
type Merge<T, U> = {[P in keyof T | keyof U]: P extends keyof U ? U[P] : P extends keyof T? T[P] : never}
36. 将大小写驼峰写法转换成短横线连接命名法
// KebabCase
// 将camelCase小驼拼写法或pascalcase大驼峰写法(第一个字符是大写的驼峰写法)字符串替换为短横线连接命名法。
// FooBarBaz -> foo-bar-baz
// 例如type FooBarBaz = KebabCase<"FooBarBaz">
const foobarbaz: FooBarBaz = "foo-bar-baz"type DoNothing = KebabCase<"do-nothing">
const doNothing: DoNothing = "do-nothing"
答案
type KebabCase<T, S extends string = ''> =T extends `${infer first}${infer other}` ?KebabCase<other, `${S}${first extends Lowercase<first> ? '' : '-'}${Lowercase<first>}`>: S extends `${'-'}${infer O}` ? O : S
37. 获取接口差值属性
// 获取两个接口类型中的差值属性。
type Foo = {a: string;b: number;}type Bar = {a: string;c: boolean}type Result1 = Diff<Foo,Bar> // { b: number, c: boolean }type Result2 = Diff<Bar,Foo> // { b: number, c: boolean }
答案
type Diff<A, B,> = {[P in Exclude<keyof A | keyof B, keyof A & keyof B>]: P extends keyof A ? A[P] : P extends keyof B ? B[P] : never
}