You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript(Ionic/Angular)推入对象时数字转字符串问题求助

Ionic/Angular TypeScript应用中number类型变量被转为字符串的问题

我在开发Ionic/Angular的TypeScript应用时,遇到一个问题:向数组推入带有默认值的对象时,number类型的timeInterval变量被转换为字符串。

类型接口定义

export interface HintsType {
    revealed?: boolean;
    type: 'string' | 'image';     
    value: any;                
    timeInterval?: number;    
}

export interface TestPieceInfo {
    seqNum: number;
    title: string;
    type: PieceTypes;
    answer: string;
    mainText: string;
    hints: HintsType[];
}

private piece: TestPieceInfo[]

相关代码

addHint() {
    console.log('BEGIN addHint:');
    this.piece.hints.push({
      revealed: false,
      type: 'string',
      value: '',
      timeInterval: 5,
    });

    console.log('END of addHint: piece=', typeof this.piece.hints[0].timeInterval, this.piece.hints);
}

控制台输出

END of addHint: piece= **number ** [{…}]
0: 
revealed: false
timeInterval: "5"
type: "string"
value: ""

[[Prototype]]: Objectlength: 1[[Prototype]]: Array(0)

代码运行时,console.log显示typeof timeInterval为'number',但在this.piece.hints数组中timeInterval显示为带引号的字符串"5",存入Google Firestore时也被存储为字符串。

已尝试的解决方法(均无效)

  • 方法1:使用类型断言

    .push({
      revealed: false,
      type: 'string',
      value: '',
      timeInterval: 5 as number
    })
    
  • 方法2:通过运算强制类型

    .push({
      revealed: false,
      type: 'string',
      value: '',
      timeInterval: 5 + 0
    })
    
  • 方法3:先设为null再赋值

    .push({ 
      revealed: false,
      type: 'string',
      value: '',
      timeInterval: null
    })
    this.piece.hints[this.piece.hints.length-1].timeInterval = 5
    

内容的提问来源于stack exchange,提问作者Rick Ford

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 12:55:21