ZhengXingchi / ZhengXingchi.github.io

Apache License 2.0
0 stars 0 forks source link

typescript #83

Open ZhengXingchi opened 4 years ago

ZhengXingchi commented 4 years ago

参考文献

三千字讲清TypeScript与React的实战技巧

React Component Props with Typescript

ZhengXingchi commented 4 years ago

Argument of type 'number' is not assignable to parameter of type 'string' giving error

参考Argument of type 'number' is not assignable to parameter of type 'string' giving error

Here is my code

const currentTimeStamp = `${(parseInt(Date.now() / 1000))}`;
const [roomName, setRoomName] = useState<string>(currentTimeStamp || '');
it throws an error in production :

Argument of type 'number' is not assignable to parameter of type 'string'. TS2345
/*answer*/
You can remove the parseInt(), because Date.now() return already a number and also Date.now() / 1000.
parseInt() is complaining because it should be given a string instead of a number.

You can do:

const currentTimeStamp = `${(Date.now() / 1000)}`;
ZhengXingchi commented 4 years ago

Argument of type 'any' is not assignable to parameter of type 'never'.ts

参考“任何”类型的参数不能分配给“never”.ts类型的参数

首先,让我们使用一个const断言来确保编译器理解每个属性body是一个元组,其中第一个元素具有filter属性而第二个元素具有group属性。(如果不是这样,那么你value[0].filter和value[1].group代码就不安全了):

  const body = {
    A: [{ filter: [{ a: "a" }] }, { group: [{ a: "a" }] }],
    B: [{ filter: [{ a: "a" }] }, { group: [{ a: "a" }] }]
  } as const;

你遇到的问题是这样的:编译器看到你array.reduce(callback, initialAccumulator)在哪里调用initialAccumulator一个带有空数组的对象,并认为这些数组必须总是没有真正的元素(例如Array<never>)。当你试图将东西推到这样一个阵列上时,它抱怨说东西不是never。您需要使用某种方式来注释或断言累加器将持有某个数组,如下所示:

  interface Filter { a: string }; // some type for Filter
  interface Group { a: string }; // some type for Group

  var a = Object.entries(body).reduce(
    (acc, [key, value]) => {
      acc.filter.push(...value[0].filter);
      acc.group.push(...value[1].group);
      return acc;
    },
    { filter: [] as Array<Filter>, group: [] as Array<Group> } 
    // assert the arrays are holding Filter and Group objects respectively
  )