【问题标题】:How to add item dynamically to tuple in TypeScript?如何将项目动态添加到 TypeScript 中的元组?
【发布时间】:2016-05-27 09:59:03
【问题描述】:

这个问题来自How to push item to [string] in TypeScript

我想创建如下函数。

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 函数需要将'param'参数设置为[string]的类型。

所以我将'param'元组声明为[string]

我想通过options['limit']options['offset'] 值动态更改参数元组。

param.push(String(limit)); 失败,因为参数未定义,所以我尝试var param: [string] = []; 然后出现语法错误。

[ts] 类型 'undefined[]' 不能分配给类型 '[string]'。类型“undefined[]”中缺少属性“0”。

我该如何解决这个问题?

提前致谢。

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    如果你真的想要一个元素元组,你只需要分配它而不是使用推送:

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

    但这不会让您同时拥有偏移量和限制。你可能想要:

     let param: string[] = []
    

    在使用.push()

    【讨论】:

    • 谢谢。我需要使用 [string] 类型,因为插件函数的设计和动态添加元组项取决于选项的数量。例如)[10, 20], [10], [20]
    • 那么它只是一个数组,而不是一个元组。 Javascript 不支持元组。 Typescript 将某些数组视为指定数量的元素,仅由 typescript 编译器控制。它会警告你,但不会阻止你做任何事情。如果一个插件说它需要一个 tuple,它仍然只是一个数组。如果你正在使用这个插件,只需传递一个数组。如果您正在生产它,那么您选择了错误的数据结构。
    【解决方案2】:

    使用var params: string[] = []; 当你使用语句var param: string[];时,你只声明它的类型,params是未定义的。
    不要使用var

    【讨论】:

    • 谢谢,但 execQuery 需要将 [string] 设置为 param 参数。
    猜你喜欢
    • 2016-07-15
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多