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

在省略和破坏子类型之后,无法构造泛型类型的对象

  •  0
  • TacB0sS  · 技术社区  · 5 年前

    typescript版本:3.7.5

    type A = { _id: string }
    type B = A & { one: string, two: string }
    type C = Omit<B, "_id">;
    
    
    const valueWithoutId: C = {one: "value-1", two: "value-2"};
    
    // This works just fine...
    const valueWithId: B = {...valueWithoutId, _id: "new-id"};
    
    console.log(valueWithId);
    
    
    function thisBreaks_butWhy<T extends A, U = Omit<T, "_id">>(_valueWithoutId: U) {
    
        // The following line breaks... Why?
        const _valueWithId: T = {..._valueWithoutId, _id: "new-id"};
    }
    

     TS2322: Type 'U & { _id: string; }' is not assignable to type 'T'.
      'U & { _id: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'A'
    

    我试着更明确地说:

    function thisBreaks_butWhy<T extends A>(_valueWithoutId: Omit<T, "_id">) {
    
        // The following line breaks... Why?
        const _valueWithId: T = {..._valueWithoutId, _id: "new-id"};
    }
    

    0 回复  |  直到 5 年前