示例代码:

/* @flow */

type Key = 'a' | 'b';

const obj: {[key: Key]: number} = {
  a: 1,
  b: 2,
};

const keys = Object.keys(obj);

const val = obj[keys[0]];


哪个produces this error message

10: const keys = Object.keys(obj);
                             ^ string. This type is incompatible with
5: const obj: {[key: Key]: number} = {
                     ^ string enum


因此它认为keysstring[]而不是Key[],这在我看来是错误的。除了将obj的类型更改为{[key: string]: number}之外,还有什么办法可以解决此问题?

最佳答案

由于Array<T>是不变的,因此流程会引发错误(请参见https://github.com/facebook/flow/issues/2487)。可以通过定义自己的keys函数来解决此问题

function keys<T: string>(obj: any): Array<T> {
  return Object.keys(obj)
}

07-24 09:43
查看更多