简体   繁体   English

如何在打字稿中按名称检查泛型类型是否具有属性?

[英]How to check whether a generic type has a property by name in typescript?

I have below code in typescript.我在打字稿中有以下代码。 In the body of the function, I'd like to check whether each key in the event exists in the type T .在函数体中,我想检查event中的每个key是否存在于类型T How can I do that in typescript ?我怎么能在typescript做到这一点?

export const convert = <T>(event: { [key: string]: any }) => {
   // how can I check whether each key in event exists in type T
}

In this function, I'd like to save the event to Postgresql table so I'd like to filter out fields which don't exist in table columns.在这个函数中,我想将event保存到 Postgresql 表,所以我想过滤掉表列中不存在的字段。

If T is removed after compilation, can I use a class to do that?如果编译后删除了T ,我可以使用class来做到这一点吗?

Like in below class, it maps to database table columns.就像下面的类一样,它映射到数据库表列。 Can I filter out the fields in the event based on the fields declared in this class?我可以根据这个类中声明的字段过滤掉event中的字段吗?

class Entity {
   @column()
   id!: string;
   @column
   name? : string;

考虑以下,但event必须输入

export const convert = <T extends Record<string, unknown>>(event: Record<keyof T, unknown>) => {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM