首页 > 解决方案 > 无法使宽度子类型与精确类型一起使用

问题描述

我通过“传播”两种确切类型创建了一个类型:

type Type1 = {|foo: number|};
type Type2 = {|bar: string|};
type Both = {|...Type1, ...Type2|};

而且我不明白为什么我不能让宽度子类型如下工作:

var a: Both = {foo: 42, bar: 'baz'};

function fooTest(arg: Type1) {
    console.log(arg.foo);
}

fooTest(a);

我收到此错误:

../\-:11: fooTest(a);
                  ^ Cannot call `fooTest` with `a` bound to `arg` because property `bar` is missing in `Type1` [1] but exists in `Both` [2]. [prop-missing]
References:
../\-:7: function fooTest(arg: Type1) {
                               ^ [1]
../\-:5: var a: Both = {foo: 42, bar: 'baz'};
                ^ [2]

但是从这个页面,我收集到我被允许传递额外的属性,但似乎确切的类型阻止了这种行为。

在这里,正确的方法是什么?

尝试一下

编辑: 感谢@Aleksey L. 的指针,我最终将函数参数的类型转换为不精确的类型:

function fooTest(arg: {...Type1}) {
    console.log(arg.foo);
}

标签: javascriptflowtype

解决方案


不,将具有“额外”属性的对象传递给确切的对象类型是无效的

精确对象类型禁用宽度子类型,并且不允许存在其他属性。

更多信息在这里


推荐阅读