【问题标题】:Get type from typeguard's type predicate从 typeguard 的类型谓词中获取类型
【发布时间】:2020-09-17 16:41:28
【问题描述】:

通常,typeguard 的类型是这样定义的:

(value: unknown) => value is Type

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

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

更进一步,我们可以说(我不知道文档是如何定义的)value 是 typeguard 的 参数is 是 TypeScript 二进制文件operator/keyword 用于定义类型谓词,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

GuaranteedType 是所需的结果。


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

【问题讨论】:

    标签: typescript typeguards


    【解决方案1】:

    您可以使用 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

    【讨论】:

      猜你喜欢
      • 2020-01-27
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 2022-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多