简体   繁体   English

当函数的参数是具有所述方法的对象时,为什么 Typescript 不能推断方法调用,该方法的输入是对象的属性?

[英]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.propsparam.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.

相关问题 为什么TypeScript在嵌套对象中不能推断泛型类型? - Why can't TypeScript infer a generic type when it is in a nested object? TypeScript 可以推断出 object 的属性吗? - Can TypeScript infer the properties of an object? 如何使 Typescript 推断对象中的通用方法参数类型 - How to make Typescript infer a generic method argument type in an object TypeScript:传递对象的方法作为参数调用 - TypeScript: Passing object's method to call as an argument 为什么Typescript不能推断出这个函数的参数类型? - Why can't Typescript infer the argument types of this function? 为什么 Typescript 不能推断出可选 arguments 的 function 参数类型? - Why can't Typescript infer function argument types for optional arguments? TypeScript:推断类型<this>在 Object 扩展方法中</this> - TypeScript: Infer type of <this> in Object extension method 为什么 TypeScript 不能推断相同对象类型的赋值? - Why TypeScript can't infer assignments of the same object type? 当您将返回类型方法的 output 分配给变量时,为什么 Typescript 无法推断类型? - Why Typescript can't infer type when you assign a return typed method's output to a variable? Typescript 根据同一对象中的属性推断函数的对象键 - Typescript infer object keys for function based on properties in the same object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM