通用类型检查器,用于检查属性是否存在

huangapple go评论63阅读模式
英文:

Generic typeguard for checking property existance

问题

这个问题的答案显示了如何创建一个类型来检查对象上的属性是否存在。

我使用了以下变体:

const hasMetadata = <T extends object>(obj: T): obj is T & {metadata: unknown} => (
Object.hasOwn(obj, 'metadata')
)


然而,我最终需要几个类似的类型守卫:我有一个包含大约20个左右的文件。我开始考虑简单的代码生成。

在此之前,我想确保在typescript中不可能实现通用属性检查的类型守卫。

它看起来像这样:

const hasProp = <T extends object>(obj: T, key: string): obj is T & {[key]: unknown} => (
Object.hasOwn(obj, key)
)


这段代码在类型检查时失败,并显示以下错误:

类型文字中的计算属性名必须引用其类型为文本字面类型或'unique symbol'类型的表达式


有人知道如何实现这样的通用类型守卫吗?
英文:

The answer to This question shows how to create a type to check that a property exists on an object.

I use the following variant :

const hasMetadata = &lt;T extends object&gt;(obj: T): obj is T &amp; {metadata: unknown} =&gt; (
	Object.hasOwn(obj, &#39;metadata&#39;)
)

However I end up needing several such typeguards : I have a file with 20 or so. I am starting to consider simple code generation.

Before that, I wanted to make sure that a generic property check type guard is not possible in typescript.

It would look like that

const hasProp = &lt;T extends object&gt;(obj: T, key: string): obj is T &amp; {[key]: unknown} =&gt; (
	Object.hasOwn(obj, key)
)

This code fails to typecheck with the following error

A computed property name in a type literal must refer to an expression whose type is a literal type or a &#39;unique symbol&#39; type

Does someone knows of a way to achieve such a generic typeguard ?

答案1

得分: 1

只需在string后输入您的key

const hasProp = <T extends object>(obj: T, key: string): obj is T & {[key: string]: unknown} => (
    Object.hasOwn(obj, key)
)
英文:

Just type your key with string !

const hasProp = &lt;T extends object&gt;(obj: T, key: string): obj is T &amp; {[key: string]: unknown} =&gt; (
    Object.hasOwn(obj, key)
)

答案2

得分: 0

一个通用的 key 参数和映射的返回类型是我正在寻找的:

const hasProp = <T extends object, K extends string>(obj: T, key: K): obj is T & {[P in K]: unknown} => (
    Object.hasOwn(obj, key)
)
英文:

A generic key argument and a mapped return type is what I was looking for :

const hasProp = &lt;T extends object, K extends string&gt;(obj: T, key: K): obj is T &amp; {[P in K]: unknown} =&gt; (
    Object.hasOwn(obj, key)
)

huangapple
  • 本文由 发表于 2023年2月16日 16:54:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75469811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定