ts中的泛型与infer

594 阅读1分钟

泛型

  • 理解 泛型是一种类型变量,作用于类型,而不是作用于值
  • 示例
// 直接返回参数
// 这里的T相当于给func函数的参数定义了一个类型变量
function func<T>(arg: T): T {
    return arg;
}

infer

  • 理解 infer相当于给extends之后的变量设置了一个类型变量,只能出现在extends子语句中
  • 示例
// 利用infer解包数组里的元素类型
type ArrayElement<
    ArrayType extends unknown[]
> = ArrayType extends (infer ElementType)[] ? ElementType : never;
let AUTH_UCODE = [
    "basic",
    "channel",
    67
];
type AuthDomain = ArrayElement<typeof AUTH_UCODE>;
// 相当于type AuthDomain = string | number
type ArrayElement<
    ArrayType extends readonly unknown[]
> = ArrayType extends readonly (infer ElementType)[] ? ElementType : never;
const AUTH_UCODE = [
    "basic",
    "channel",
    67
] as const;
type AuthDomain = ArrayElement<typeof AUTH_UCODE>;
// 限制只读
// 相当于type AuthDomain = "basic" | "channel" | 67