无法获得宽度子类型以使用精确类型
Cannot get width subtyping to work with exact types
我通过“传播”2 个确切类型创建了一个类型:
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]
但是从 this page,我了解到我被允许传递额外的属性,但似乎确切的类型阻止了这种行为。
正确的做法是什么?
编辑:
感谢@Aleksey L. 的指点,我最终将我的函数参数的类型变成了一个不精确的类型:
function fooTest(arg: {...Type1}) {
console.log(arg.foo);
}
不,将具有“额外”属性的对象传递给确切的对象类型是无效的
Exact object types disable width subtyping, and do not allow additional properties to exist.
更多信息here
我通过“传播”2 个确切类型创建了一个类型:
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]
但是从 this page,我了解到我被允许传递额外的属性,但似乎确切的类型阻止了这种行为。
正确的做法是什么?
编辑: 感谢@Aleksey L. 的指点,我最终将我的函数参数的类型变成了一个不精确的类型:
function fooTest(arg: {...Type1}) {
console.log(arg.foo);
}
不,将具有“额外”属性的对象传递给确切的对象类型是无效的
Exact object types disable width subtyping, and do not allow additional properties to exist.
更多信息here