【问题标题】:Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string''string | 类型的参数number' 不可分配给“字符串”类型的参数。类型“数字”不可分配给类型“字符串”
【发布时间】:2019-12-18 12:17:40
【问题描述】:

我有:

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 | 类型的参数number' 不可分配给参数 输入“字符串”。类型“数字”不可分配给类型“字符串”

我做错了什么,我该如何解决?

【问题讨论】:

  • 你从哪里得到这个错误的?
  • moment.unix(arg)。 arg 应该是 number 而不是 number | string
  • 不能分配给'string'类型的参数。

标签: javascript typescript


【解决方案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')
}));

【讨论】:

    猜你喜欢
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2021-09-07
    • 2021-02-03
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多