简体   繁体   English

如何定义正确的地图 <X,Y> 输入打字稿,其中Y将是Parent的任何子类?

[英]How to define correct Map<X,Y> type in typescript where Y will be any child class of Parent?

I have some Parent class and amount of Child classes that extends parent. 我有一些Parent类和大量扩展父类的Child类。 I need to define Map<sting,Y> where Y can be any of Child classes. 我需要定义Map<sting,Y> ,其中Y可以是任何Child类。 If I try to define it as Map<string, Parent> I got transpilation error 如果我尝试将其定义为Map<string, Parent>则会发生翻译错误

error TS2345: Argument of type 'typeof Child' is not assignable to parameter of type 'Parent'. 错误TS2345:类型'typeof Child'的参数不能分配给'父母'类型的参数。 Property 'someParentMethod' is missing in type 'typeof Child'. 属性“ typeof Child”中缺少属性“ someParentMethod”。

As Child automatically inherits someParentMethod from Parent I don't re declare in Child class. 因为Child自动从Parent继承了someParentMethod ,所以我不在Child类中进行声明。 What is the correct way of declare needed Map argument type, so that it accepted any Child class instances? 声明所需的Map参数类型以使其接受任何Child类实例的正确方法是什么?

Looks like you are only missing a typeof . 看起来您只缺少typeof

class a { public x; someParentMethod: () => void }
class b extends a { }

let m: Map<string, typeof a> = new Map([['a', b]]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在打字稿中以xy形式定义接口? - How can i define interface in x.y form in typescript? 打字稿 + useRef<X|Y> : X 型不能分配给 Y 型 - TypeScript + useRef<X|Y>: Type X is not assignable to type Y 如何定义要避免的属性:类型“Y”上不存在属性“X” - How to define a property to avoid: Property 'X' does not exist on type 'Y' 类型“X”不可分配给带有打字稿的“Y”类型 - Type"X' is not assignable to type "Y" with typescript Typescript泛型,类型&#39;X&#39;不能赋值为&#39;Y&#39; - Typescript generics, Type 'X' is not assignable to type 'Y' 打字稿编译错误: <x> 不可分配给类型 <y> - Typescript compilation error: <x> is not assignable to type <y> 打字稿:X 类型的参数不能分配给 Y 和 X 类型的参数。X 类型不能分配给 Y 类型 - Typescript: Argument of type X is not assignable to parameter of type Y & X. Type X is not assignable to type Y TypeScript:从“ Y”导入{X}-如何替换/重定向Y - TypeScript: import { X } from 'Y' - how to substitute/redirect Y TypeScript 如何强制执行多种类型选项,类型“Y”上不存在属性“X” - TypeScript how to enforce a type of multiple type options, Property 'X' does not exist on type 'Y' Typescript - “X”类型的参数不能分配给“Y”类型的参数 - Typescript - Argument of type “X” is not assignable to parameter of type “Y”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM