不兼容的对象类型

时间:2018-09-11 06:55:01

标签: flowtype

/* @flow */

type optionsType = Array<{id: string | number, name: string}>;
type modelsType = Array<{id: number, name: string}>;

function getOptions(options: optionsType): string {
  return options.reduce((a, e) => {
    return a + `<option value="${e.id.toString()}">${e.name}</option>`;
  }, '');
}

const options: modelsType = [
  {id: 1, name: 'punto'},
  {id: 2, name: 'duo'},
  {id: 500, name: 'cinquecento'},
];
console.log(getOptions(options));

以上示例抱怨Cannot call "getOptions" with "options" bound to "options" because number [1] is incompatible with string [2] in property "id" of array element.,但据我了解,modelsTypeoptionsType更通用。为什么流程会抱怨,我如何才能按预期工作?

2 个答案:

答案 0 :(得分:2)

如果

let second: secondType = first;

被允许原样使用,这意味着这样做是有效的

second.id = "some-id";

但这会破坏firstType的类型,因为它是同一对象,并且类型为number,但是现在已为其分配了字符串。

要使此工作有效,您需要说secondType.id是只读的或“协变量”。您可以通过更改

来实现
type secondType = {id: string | number, name: string};

type secondType = {+id: string | number, name: string};

Example on flow.org/try

答案 1 :(得分:0)

我的用例的最终解决方案:

/* @flow */

type optionsType = $ReadOnlyArray<{+id: string | number, name: string}>;
type modelsType = Array<{id: number, name: string}>;

function getOptions(options: optionsType): string {
  return options.reduce((a, e) => {
    return a + `<option value="${e.id.toString()}">${e.name}</option>`;
  }, '');
}

const options: modelsType = [
  {id: 1, name: 'punto'},
  {id: 2, name: 'duo'},
  {id: 500, name: 'cinquecento'},
];
console.log(getOptions(options));