javascript - 无法使宽度子类型与精确类型一起使用
问题描述
我通过“传播”两种确切类型创建了一个类型:
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);
}
解决方案
推荐阅读
- php - Symfony/Api Platform/Schema Generator:定义双向多对多关系
- netsuite - 在客户记录表单上创建自定义字段,显示从年初至今的总交易
- haproxy - Haproxy:如何切换回主服务器
- jenkins - 詹金斯:代理与代理/节点
- mongodb - 在 MongoDB 中使用嵌套的对象数组对多个文档进行分组
- javascript - 你如何一起传递多个包装好的道具
- python - 带有权限策略的无头 Chrome 错误
- swift - WatchOS 8 按下其中一个侧边按钮会关闭模式表
- python - 在 for 循环中分别增加 2 个不同的参数
- python - 在streamlit中加载模型进行预测时Mask Rcnn模型形状错误