从类型保护的类型谓词中获取类型

Get type from typeguard's type predicate

通常,typeguard 的类型定义如下:

(value: unknown) => value is Type

其中突出显示的部分被 documentation 称为 类型谓词 :

(value: unknown) => **value is Type**

更进一步,我们可以说(我不知道文档是如何定义的)value 是类型保护的 参数 is 是一个 TypeScript 二进制 operator/keyword 用于定义类型谓词,Type 是类型保护实际保证的类型, 保证类型。 由于我们使用类型保护来保证值的类型,我们可以说 Type 是定义中最有趣的部分。

既然如此,是否可以从类型保护的类型定义中提取 Type?怎么样?

我在想类似的东西:

type Type = typeof typeguard; // (value: unknown) => value is Type
type TypePredicate = TypePredicateOf<Type>; // value is Type
type GuaranteedType = IsOf<TypePredicate>; // Type

其中 GuaranteedType 是所需的结果。


谷歌搜索,我只找到了关于 generic typeguards 类型定义的答案,但没有得到如何从中获取 Type 部分。

您可以使用 conditional type inferenceinfer 关键字来从类型保护签名中提取保护类型。类似于:

type GuardedType<T> = T extends (x: any) => x is infer U ? U : never;

并给出一些用户定义的类型保护:

function isString(x: any): x is string {
  return typeof x === "string";
}

interface Foo {
  a: string;
}

function isFoo(x: any): x is Foo {
  return "a" in x && typeof x.a === "string"
}

您可以看到它像宣传的那样工作:

type S = GuardedType<typeof isString>; // string
type F = GuardedType<typeof isFoo>; // Foo

好的,希望对您有所帮助;祝你好运!

Playground link to code