filter out unneeded object properties for interface in typescript

霸气de小男生 提交于 2019-12-11 06:37:13

问题


As background, I'm using Prisma (graphql), mysql2 (nodejs) and typescript.

I'm using an interactive command line script to connect to mysql2.

This is the warning I am seeing:

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

This is how I instantiate mysql2, in my MysqlConnector class:

this.connectionPromise = await this.mysql.createConnection(this.connectionOptions)

"connectionOptions" is set in the class constructor:

constructor(connectionDetails: MysqlConnectionDetails) {

This is my type definition:

export interface MysqlConnectionDetails {
  host: string
  port: number
  user: string
  password: string
  database?: string
}

This is the type definition of the object that I pass into my MysqlConnector class:

export interface DatabaseCredentials {
  type: DatabaseType
  host: string
  port: number
  user: string
  password: string
  database?: string
  alreadyData?: boolean
  schema?: string
  ssl?: boolean
  filter?: any
}

So, I am passing in an object that has additional parameters that mysql2 does not want/need. I am new to Typescript. I tried this, before passing the object in to the MysqlConnector class:

let forDeletion = ['type', 'alreadyData']
connector = new MysqlConnector(credentials.filter(item => !forDeletion.includes(item)))

But I get an error, saying "filter" is not a property on the type "DatabaseCredentials", and I concluded this is probably not the right way to do this.

I assumed there is a way in Typescript (through tsconfig) automatically to filter out properties that are not in the receiving type. "MysqlConnectionDetails" doesn't have a property "type", in its definition, so it gets it dynamically, when I pass in another type.


回答1:


Not sure if there's a specific TypeScript way to deal with this, but you can use destructuring/spread for this:

const { type, ...validCredentials } = credentials;

This essentially picks type out of credentials, and validCredentials will contain the rest of the properties.

The reason .filter didn't work is because filter is a prototype method on arrays, not objects.




回答2:


If you insist on using Array methods, .map() is probably most helpful:

let obj2big = { a: 1, b: 2, c: 3 }

// let's assume what you want from this is { a: 1, c: 3 }

let arr = [obj2big]

let result = arr.map(i=>({a:i.a, c: i.c}))

console.log(result[0])


来源:https://stackoverflow.com/questions/52190091/filter-out-unneeded-object-properties-for-interface-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!