【问题标题】:Equivalent types but unassignable when using optional index signature : why?等效类型但在使用可选索引签名时不可分配:为什么?
【发布时间】:2021-03-22 03:49:39
【问题描述】:

我有以下情况:

type FilterQuery<T> = { [P in keyof T]?: T[P] } & RootQuerySelector<T>;

type RootQuerySelector<T> = {
  $and?: Array<FilterQuery<T>>;
}

class A<T> {
    queries: Array<FilterQuery<T>>

    constructor() {
        this.queries = []
    }

    stuff() {
        const query: FilterQuery<T> = { $and: this.queries }
        console.log(query)
    }
}

stuff() 中的 query 赋值被 TS 标记为错误:

const query: FilterQuery<T>
  Type '{ $and: FilterQuery<T>[]; }' is not assignable to type 'FilterQuery<T>'.
    Type '{ $and: FilterQuery<T>[]; }' is not assignable to type '{ [P in keyof T]?: T[P] | undefined; }'.(2322)

Playground Link

我原以为{ $and: this.queries } 是一个有效的FilterQuery,因为它是RootQuerySelector 允许的形状(顺便说一句,这些类型来自MongoDB 官方节点驱动程序)。

为什么这里会出现问题,我该如何解决?谢谢。

【问题讨论】:

  • 我之前接触过this kind of thing。有了这些知识,您可以将两个值毫无错误地传播到结果对象中。 See here
  • 除非我记错了,{ [P in keyof T]?: T[P] }Partial&lt;T&gt; 对吧?
  • 是的,确实如此。并传播作品,谢谢

标签: typescript


【解决方案1】:

这很可能是一个错误。编译器在评估您的对象时遇到问题,因为还没有类型信息。在为T 设置真实类型之前,他不知道{ [P in keyof T]?: T[P] } 解析为什么。如果你把{ [P in keyof T]?: T[P] } 带走,他不会抱怨的。但是你可以欺骗编译器(playground):

class A<T> {
    queries: Array<FilterQuery<T>>

    constructor() {
        this.queries = []
    }

    stuff() {
        const query: FilterQuery<T> = {};
        query.$and = this.queries;
        console.log(query)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 2017-01-26
    相关资源
    最近更新 更多