openlang

让 TypeScript 数组接受同一父类派生的对象

我想用一个变量保存类实例数组,元素类型要允许任何从某个“基类”派生的实例。这个类实例数组的例子能更清楚地说明我的意思。

class Parent { } //Common parent
class FirstChild extends Parent { }
class SecondChild extends Parent { }

//How should this declaration look?
let instances: <U extends Parent>U[] = []; //Allow all descedants of 'Parent' here

//Then these calls would work
instances.push(new Parent());
instances.push(new FirstChild());
instances.push(new SecondChild());

先谢谢大家。

从英语翻译查看原文

后续讨论 2

顺着彼此的依据读下去
  1. 固定链接

    你的类实例数组也可以用这种方式

    type Family = Parent | FirstChild | SecondChild;
    let instances: Array<Family> = new Array<Family>();
    从英语翻译查看原文

同一个问题的其他角度

  1. 初始化以字符串数组为值的 TypeScript Map

    我在创建一个 Map,其中每个条目都保存字符串数组。怎样在一条语句中同时声明类型并完成初始化? 我(天真地)这样试了一下。 结果是下面这个错误。

    回复 2最近活动 typescript
  2. Typescript 可调用函数的约定

    为什么 Typescript 接受我的函数定义,虽然它与接口签名不同,但当我实际调用同一个函数时却报告问题。

    回复 2最近活动 typescript
  3. Solidity 从 address 转换为 uint256 时失败

    我创建了一个包含结构体的数组,然后尝试从该数组取得每个账号的值。但传入包含 msg.sender 的 address 变量时失败了,因为它的类型似乎无法转换为 uint256。应该怎样实现?

    回复 3最近活动 solidity