简体   繁体   中英

Typescript optional parameter breaks query

I am trying to create a function with a optional parameter, however:

async find(query: string, parameters?: string): Promise<T[]> {
    const stmt: sqlite3.Statement = await this.db.prepare(query)
    const info: T[] = stmt.all(parameters)
    this.db.close()

    return info
}

If I provide no parameters, I still get the error: RangeError: Too many parameter values were provided , how can I make parameters actually nothing if none is provided?

You appear to be using the sqlite3 npm package. I've never used this library before, but from their API documentation it appears that you'll want to pass in an object or array as parameters rather than a simple string as a parameter (which would be undefined if you called find with only one argument).

// Key-value pairs as parameters
async find(query: string, parameters: Record<string, any> = {}): Promise<T[]> {
    const stmt: sqlite3.Statement = await this.db.prepare(query)
    const info: T[] = stmt.all(parameters)
    this.db.close()

    return info
}

// Array of parameters
async find(query: string, ...parameters: any[]): Promise<T[]> {
    const stmt: sqlite3.Statement = await this.db.prepare(query)
    const info: T[] = stmt.all(parameters)
    this.db.close()

    return info
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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