泛型扩展某些类的问题

问题描述 投票:0回答:2

为什么我在qazxsw poi,qazxsw poi,qazxsw poi中出错?所有这些都匹配e4类型,所以他们必须匹配通用e5

e6

我最终希望SomeClass返回RES,但为了这个例子,我简化了它。

typescript
2个回答
2
投票

class SomeClass { a: string; b: number; c: boolean; } class ChildOfSomeClass extends SomeClass {} const someFunc1 = <RES extends SomeClass>() => { const e1: SomeClass = { a: "aaa", b: 123, c: true }; // ok const e2: SomeClass = new SomeClass(); // ok const e3: SomeClass = new ChildOfSomeClass(); // ok // Type '{ a: string; b: number; c: true; }' is not assignable to type 'RES'.ts(2322) const e4: RES = { a: "aaa", b: 123, c: true }; // Type 'SomeClass' is not assignable to type 'RES'.ts(2322) const e5: RES = new SomeClass(); // Type 'ChildOfSomeClass' is not assignable to type 'RES'.ts(2322) const e6: RES = new ChildOfSomeClass(); }; 表示由someFunc1类型描述的值集合是由RES | Promise<RES>类型描述的值集合的子集。想象一下以下场景:

RES extends SomeClass

这满足条件RES,但是在你提供的所有构造函数的情况下,你都没有指定SomeClass

有很多方法可以解决这个问题,“正确”的解决方案将取决于您使用此方法尝试完成的内容。例如,一种解决方案是使您的方法采用一些构造函数或转换器方法从class MyRES extends SomeClass { d: string; } 的已知现有属性创建RES extends SomeClass

d

1
投票

这是因为RES扩展了SomeClass。想象一下:

const someFunc1 = <RES extends SomeClass>(toRes: (SomeClass) => RES) => {
  const e: RES = toRes({ a: "aaa", b: 123, c: true }); // ok
};

并且假设RESSomeClass(它确实扩展了class SomeClass { a: string; b: number; c: boolean; } class ChildOfSomeClass extends SomeClass {} class OtherChild extends SomeClass { d: string } ),你的代码看起来像:

RES

你可以通过使用OtherChild来解决这个问题,然后传递任何子对象都可以。

© www.soinside.com 2019 - 2024. All rights reserved.