java 动态数组添加元素_动态添加元素到类型化数组

我可以将一个类型数组传递给构造函数,并使用泛型来声明类型 . 但是在获取对象实例(通过构造函数调用)之后,我想向数组添加一个新元素 . 但我现在拥有的动态类型化方法无法将新元素合并到数组中 .

说我有这个:

type TypeMapping = {

Boolean: boolean,

String: string,

Number: number,

Integer: number,

}

export enum Type {

Boolean = 'Boolean',

String = 'String',

Number = 'Number',

Integer = 'Integer',

}

export interface ElemType {

name: string,

type: keyof TypeMapping,

}

export const asOptions = >(t: T) => t;

export type OptionsToType>

= { [K in T[number]['name']]: TypeMapping[Extract['type']] }

export class Foo> {

bar: T;

baz: OptionsToType;

constructor(t: T){

this.bar = t;

}

add(t: ElemType){

this.bar.push(t);

}

}

const list = asOptions([{name: 'xxx', type: Type.Boolean}]);

const f = new Foo(list);

f.baz.xxx = false; // compiles

f.add({name: 'uuu', type: Type.String});

f.baz.uuu = 'z'; // does not compile (as we would expect)

它工作得很好,直到最后两行 . 如果我使用 add() 方法将新元素推送到数组上,那么类型系统实际上无法合并 .

有没有一些神奇的方法可以更新实例上bar / baz成员的类型?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值