代码之家  ›  专栏  ›  技术社区  ›  skube

“…”类型的参数不能分配给“…”类型的参数ts 2345

  •  0
  • skube  · 技术社区  · 6 年前

    鉴于以下情况:

    interface MyInterface {
      type: string;
    }
    
    let arr:object[] = [ {type: 'asdf'}, {type: 'qwerty'}]
    
    // Alphabetical sort
    arr.sort((a: MyInterface, b: MyInterface) => {
          if (a.type < b.type) return -1;
          if (a.type > b.type) return 1;
          return 0;
        });
    

    有人能帮忙破译TS错误吗?

    // TypeScript Error
    [ts]
    Argument of type '(a: MyInterface, b: MyInterface) => 0 | 1 | -1' is not assignable to parameter of type '(a: object, b: object) => number'.
      Types of parameters 'a' and 'a' are incompatible.
        Type '{}' is missing the following properties from type 'MyInterface': type [2345]
    
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   basarat    6 年前

    下面是重现错误的简化示例:

    interface MyInterface {
      type: string;
    }
    let arr:object[] = []
    // Error: "object" is not compatible with MyInterface 
    arr.sort((a: MyInterface, b: MyInterface) => {});
    

    出错的原因是 object 无法分配给类型为的内容 MyInterface :

    interface MyInterface {
      type: string;
    }
    declare let foo: object;
    declare let bar: MyInterface;
    // ERROR: object not assignable to MyInterface
    bar = foo; 
    

    这是一个错误的原因是 对象 与…同义 {} . {} 没有 type 属性,因此与MyInterface不兼容。

    固定

    也许你想用 any 而不是 对象 ) 任何 与兼容 一切 .

    更好的解决办法

    使用准确的类型,即 My接口

    interface MyInterface {
      type: string;
    }
    let arr:MyInterface[] = []; // Add correct annotation 🌹
    arr.sort((a: MyInterface, b: MyInterface) => {});