类型'string |çš„å‚æ•°æ•°å­—â€ä¸èƒ½åˆ†é…给“字符串â€ç±»åž‹çš„å‚数。 “数字â€ç±»åž‹ä¸èƒ½åˆ†é…给“字符串â€ç±»åž‹

时间:2019-12-18 12:17:40

标签: javascript typescript

我有:

export interface MyObject  {
  id: number;
  name: string;
  timestamp: number | string;
}

默认情况下,时间戳是一个数字,但我想使用momentjs将其转æ¢ä¸ºâ€œ HH:mm:ss DD / MM / YYYYâ€æ ¼å¼çš„字符串。

const myArray: MyObject[] = [{id: 1, name: 'foo', timestamp: 123},{id: 2, name: 'bar', timestamp: 456}];

我正在使用.forEach以便将所有时间戳转æ¢ä¸ºå­—符串:

myArray.forEach(el => el.timestamp = moment.unix(el.timestamp).format('HH:mm:ss DD/MM/YYYY'));

但是,我在moment.unix呼å«ä¸­æ”¶åˆ°æ­¤é”™è¯¯ï¼š

  

'string |类型的å‚æ•°æ•°å­—â€ä¸èƒ½åˆ†é…给的å‚æ•°   输入“字符串â€ã€‚ä¸èƒ½å°†â€œæ•°å­—â€ç±»åž‹åˆ†é…给“字符串â€ç±»åž‹

我在åšä»€ä¹ˆé”™ï¼Œå¦‚何解决?

1 个答案:

答案 0 :(得分:1)

moment.unix仅接å—数字作为å‚数:

https://github.com/moment/moment/blob/develop/moment.d.ts

export function unix(timestamp: number): Moment;

因此,在将timestamp传递给moment.unix之å‰ï¼Œè¯·ç¡®ä¿å…¶ä¸ºæ•°å­—:

myArray.forEach((el) => {
  const { timestamp } = el;
  if (typeof timestamp === 'number') {
    el.timestamp = moment.unix(timestamp).format('HH:mm:ss DD/MM/YYYY')
  } else {
    // will this ever happen? Do whatever you want here - ignore it, or throw
  }
});

您还å¯ä»¥ä½¿ç”¨ä¸¤ç§å¯¹è±¡ç±»åž‹-一ç§ç”¨äºŽæ•°å­—时间戳,一ç§ç”¨äºŽå­—符串格å¼ï¼Œå¹¶ä½¿ç”¨.map:

export type MyObjectNumTimestamps = {
  id: number;
  name: string;
  timestamp: number;
};
export type MyObjectStringTimestamps = {
  id: number;
  name: string;
  timestamp: number;
};

,最åˆå°†æ•°ç»„声明为类型MyObjectNumTimestamps,然åŽå°†å…¶è½¬æ¢ä¸ºMyObjectStringTimestamps:

const transformedArray: MyObjectStringTimestamps[] = myArray.map(el => ({
  ...el,
  timestamp: moment.unix(el.timestamp).format('HH:mm:ss DD/MM/YYYY')
}));
相关问题