英文:
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 = <T extends object>(obj: T): obj is T & {metadata: unknown} => (
Object.hasOwn(obj, 'metadata')
)
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 = <T extends object>(obj: T, key: string): obj is T & {[key]: unknown} => (
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 'unique symbol' 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 = <T extends object>(obj: T, key: string): obj is T & {[key: string]: unknown} => (
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 = <T extends object, K extends string>(obj: T, key: K): obj is T & {[P in K]: unknown} => (
Object.hasOwn(obj, key)
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论