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

时间:2020-10-28 10:36:42

标签: typescript

我在打字稿中有以下代码。在函数的主体中,我想检查key中的每个event是否以类型T存在。如何在typescript中做到这一点?

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

在此函数中,我想将event保存到Postgresql表中,以便过滤掉表列中不存在的字段。

如果T在编译后被删除,我可以使用class来做到这一点吗?

类似于下面的类,它映射到数据库表列。我可以根据此类中声明的字段过滤掉event中的字段吗?

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

1 个答案:

答案 0 :(得分:0)

请考虑以下内容,但还必须键入event

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