如何解决打字稿中的“无法分配”错误?

时间:2019-06-04 15:45:38

标签: typescript

我写了一个简单的类,该错误使人无聊。

class C {
  static find<T extends typeof C>(
    this: T,
    selector?: { [P in keyof InstanceType<T>]?: (InstanceType<T>)[P] },
  ) {
    // error: Type '{ id: 1; }' is not assignable
    /// to type '{ [P in keyof InstanceType<T>]?: InstanceType<T>[P]; }'.ts(2322)
    if (!selector) selector = { id: 1 };

    return Collection.find(selector);
  }

  id: number;
}

我该如何解决?

2 个答案:

答案 0 :(得分:1)

问题是,子级T中可能存在约束,而父级C中没有约束。您面对的情况类似于这种情况,在这种情况下,孩子的类型比父母的类型窄:

type Parent = { id: number; }

type Child = { id: 10 }

type ExtendsParent<T extends Parent> = T;

const p: Parent = { id: 1 };

// Type 'Parent' is not assignable to type 'Child'.
// Types of property 'id' are incompatible.
// Type 'number' is not assignable to type '10'.
const c: ExtendsParent<Child> = p;

由于Child类型的范围可能比Parent的范围窄,因此我们可以安全地将Child分配给Parent,但是不能分配{{1} }到Parent

在您的方案中,可能的解决方案(如果您认为自己比编译器更了解),将使用如下类型的断言:

Child

以上是所有in the playground(没有所有额外的selector = { id: 1 } as typeof selector; 东西)。

答案 1 :(得分:0)

可以选择:

Optional(Error Domain=GKErrorDomain Code=15 "The requested operation could not be completed because this application is not recognized by Game Center." UserInfo={GKServerStatusCode=5019, NSLocalizedDescription=The requested operation could not be completed because this application is not recognized by Game Center., NSUnderlyingError=0x60000330f180 {Error Domain=GKServerErrorDomain Code=5019 "status = 5019, no game matching descriptor: ios:com.myteam.platform:1.0:1+-1" UserInfo={GKServerStatusCode=5019, NSLocalizedFailureReason=status = 5019, no game matching descriptor: ios: com.myteam.platform:1.0:1+-1}}})