题目
实现TrimLeft
类型,将T
类型的左空格去掉
type TrimLeft<T extends string> = any
使用infer
实现:
type WhiteSpace = ' '
type TrimLeft<T extends string> =
T extends `${WhiteSpace}${infer U}` ?
TrimLeft<U>:
T
type Test = TrimLeft<' foo'> // 'foo'
总结
infer
关键字需要在extends
子句中使用,Infer 允许我们在约束中定义要引用或返回的变量。
最经典的使用场景是获取函数的返回值类型
type ReturnType<T> = T extends (...args: any) => infer U ? U : unknown
const fn = () => {
return 'fn return a string'
}
type Fn = ReturnType<fn> // 'string'