[英]Why can't Typescript infer method call when an argument to a function is an object with said method whose inputs are properties on the object?
Why isn't Typescript smart enough to figure out that the example below can't have an error in practice:为什么 Typescript 不够聪明,无法弄清楚下面的示例在实践中不会出错:
interface M1 {
props: {
color: 'red' | 'blue';
transparency: 0 | 1;
},
f: (props: M1['props']) => string
}
interface M2 {
props: {
age: number;
country: string;
},
f: (props: M2['props']) => string
}
const myFunc = (param: M1 | M2) => {
return param.f(param.props)
}
myFunc
's parameter will either be M1 or M2, but not both; myFunc
的参数将是 M1 或 M2,但不能同时是两者; so whichever it is, when you call param.f(params.props)
, you know that params.props
is of the same type as the input of param.f
.所以无论是什么,当你调用
param.f(params.props)
,你知道params.props
与param.f
的输入是相同的类型。
Is this logic incorrect or why can't TS infer this?这个逻辑是错误的还是为什么 TS 不能推断出这个?
One way to work around that limitation would be to create a superinterface M
, and define the method on M
using a polymorphic this
type :解决该限制的一种方法是创建一个超级接口
M
,并使用this
类型的多态在M
上定义方法:
interface M {
props: { [name: string]: any };
f: (props: this['props']) => string;
}
interface M1 extends M {
props: {
color: 'red' | 'blue';
transparency: 0 | 1;
}
}
interface M2 extends M {
props: {
age: number;
country: string;
}
}
const myFunc = (param: M) => {
return param.f(param.props);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.