作为背景,我使用 Prisma (graphql)、mysql2 (nodejs) 和 typescript。
我正在使用交互式命令行脚本连接到 mysql2。
这是我看到的警告:
Ignoring invalid configuration option passed to Connection: type. This is currently a warning, but in future versions of MySQL2, an error will be thrown if you pass an invalid configuration options to a Connection
这就是我在 MysqlConnector 类中实例化 mysql2 的方式:
this.connectionPromise = await this.mysql.createConnection(this.connectionOptions)
“connectionOptions”在类构造函数中设置:
constructor(connectionDetails: MysqlConnectionDetails) {
这是我的类型定义:
export interface MysqlConnectionDetails {
host: string
port: number
user: string
password: string
database?: string
}
这是我传递到 MysqlConnector 类中的对象的类型定义:
export interface DatabaseCredentials {
type: DatabaseType
host: string
port: number
user: string
password: string
database?: string
alreadyData?: boolean
schema?: string
ssl?: boolean
filter?: any
}
因此,我传入的对象具有 mysql2 不想要/不需要的附加参数。我是 typescript 新手。在将对象传递给 MysqlConnector 类之前,我尝试了此操作:
let forDeletion = ['type', 'alreadyData']
connector = new MysqlConnector(credentials.filter(item => !forDeletion.includes(item)))
但是我收到一个错误,说“filter”不是“DatabaseCredentials”类型的属性,我得出的结论是这可能不是执行此操作的正确方法。
我假设 Typescript 中有一种方法(通过 tsconfig)自动过滤掉不属于接收类型的属性。 “MysqlConnectionDetails”在其定义中没有属性“type”,因此当我传入另一个类型时,它会动态获取它。
最佳答案
不确定是否有特定的 TypeScript 方法来处理此问题,但您可以使用解构/扩展:
const { type, ...validCredentials } = credentials;
这实际上是从凭据中选择type
,而validCredentials
将包含其余属性。
.filter
不起作用的原因是 filter 是数组而不是对象的原型(prototype)方法。
关于javascript - 过滤掉 typescript 中接口(interface)不需要的对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52190091/