0

this question comes from How to push item to [string] in TypeScript

I want to create function like below.

declare var sqlitePlugin:any;

getItems(options, callback) {

  var query: string = `SELECT item_code,
                        item_name
                      FROM items `;

  var param: [string];

  if (options['limit']) {
    var limit = options['limit'];
    query = query + " LIMIT ? ";
    param.push(String(limit));
  }

  if (options['offset']) {
    var offset = options['offset'];
    query = query + " OFFSET ? ";
    param.push(String(offset));
  }

  this.execQuery(query, param, (resultSet)=>{
    this.items = [];
    for(let i = 0; i < resultSet.rows.length; i++) {
      var item: Item = new Item();
      item.code = resultSet.rows.item(i).item_code;
      item.name = resultSet.rows.item(i).item_name;
      this.artists.push(item);
    }
    callback(this.items);
  } );
}

execQuery function needs to be set 'param' parameter as type of [string].

So I declared 'param' tuple as [string].

I want to change param tuple dynamically by options['limit'] and options['offset'] value.

But param.push(String(limit)); fails because param is undefined so I tried var param: [string] = []; then syntax error occurred.

[ts] Type 'undefined[]' is not assignable to type '[string]'. Property '0' is missing in type 'undefined[]'.

How do I solve this problem?

Thanks in advance.

2 Answers 2

1

If you truly want to have a single element tuple, you need just assign it instead of using push:

let param: [string];

if (options['limit']) {
    let limit = options['limit'];
    query = query + " LIMIT ? ";
    param = [String(limit)];
}

But this won't allow you to have both an offset and a limit. You probably want:

 let param: string[] = []

while using .push()

Sign up to request clarification or add additional context in comments.

2 Comments

thanks. I need to use [string] type because plugin function's design and dynamically add tuple item depends on number of options. ex) [10, 20], [10], [20]
Then it's just an array, not a tuple. Javascript doesn't support tuples. Typescript treats certain arrays as a specified number of elements, only governed by the typescript compiler. It will warn you, but it won't prevent you from doing anything. If a plugin says it's requiring a tuple, it's still just an array. If you're consuming this plugin, just pass an array. If you're producing it, you've chosen the wrong data structure.
0

Use var params: string[] = []; When you use statement var param: string[];, you only declare its type, params is undefined.
Don't use var.

1 Comment

thanks, but execQuery needs to set [string] as param parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.