类型'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')
}));
相关问题