从 typeguard 的类型谓词获取类型

Hen*_*rra 10 typescript typeguards

通常,类型保护的类型定义如下:

(value: unknown) => value is Type
Run Code Online (Sandbox Code Playgroud)

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

(value: unknown) => **value is Type**
Run Code Online (Sandbox Code Playgroud)

甚至更进一步,我们可以说(我不知道文档是如何定义这一点的)是valuetypeguard 的参数is是用于定义类型谓词的 TypeScript 二元运算/关键字,并且Type是 typeguard 实际保证的类型,保证型。由于我们使用类型保护来保证值的类型,因此我们可以说这Type是定义中最有趣的部分。

既然如此,是否可以Type从类型保护的类型定义中提取出来?如何?

我在想这样的事情:

type Type = typeof typeguard; // (value: unknown) => value is Type
type TypePredicate = TypePredicateOf<Type>; // value is Type
type GuaranteedType = IsOf<TypePredicate>; // Type
Run Code Online (Sandbox Code Playgroud)

GuaranteedType想要的结果在哪里。


谷歌搜索后,我只找到了有关通用类型保护类型定义的答案,但没有找到如何Type从中获取该部分。

jca*_*alz 20

您可以使用带有关键字的条件类型infer推断来从类型保护签名中提取受保护的类型。就像是:

type GuardedType<T> = T extends (x: any) => x is infer U ? U : never;
Run Code Online (Sandbox Code Playgroud)

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

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"
}
Run Code Online (Sandbox Code Playgroud)

您可以看到它的工作原理如广告所示:

type S = GuardedType<typeof isString>; // string
type F = GuardedType<typeof isFoo>; // Foo
Run Code Online (Sandbox Code Playgroud)

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

Playground 代码链接