首页 文章

使用type作为值 - 在引用类型的数组上添加属性

提问于
浏览
0

假设我们有一个这样的数组:

const v = [
 {name: 'foo', type: 'Boolean' },
 {name: 'bar', type: 'String' },
 {name: 'baz', type: 'JSON' },
];

很简单,但是如果我们想添加一个type属性呢:

const v = [
 {name: 'foo', type: 'Boolean' },
 {name: 'bar', type: 'String' },
 { 
  name: 'baz', 
  type: 'JSON' 
  typeOverride: Array<{z:string, v: boolean}>  // does not work, of course
 }
];

但当然这不起作用,我们不能使用类型作为这样的值 - 我想知道是否有办法以某种方式向数组元素添加类型属性 .

像这样的东西:

const addTypeProperty = <T>(v: Elem) => v;

const v = [
 {name: 'foo', type: 'Boolean' },
 {name: 'bar', type: 'String' },
 addTypeProperty<Array<{z:string, v: boolean}>>({ 
  name: 'baz', 
  type: 'JSON' 
 })
];

有谁知道我在说什么?也许我可以使用装饰师?

addTypeProperty 需要以某种方式将typeOverride属性添加到参数中 .

1 回答

  • 0

    我认为这是对的,但不太确定:

    'use strict';
    
    interface Elem <T = any>{
      name: string,
      type: string,
      typeOverride?: T
    }
    
    const addTypeProperty = <T>(v: Elem): Elem<T> => v;
    
    const v : Array<Elem> = [
      {name: 'foo', type: 'Boolean' },
      {name: 'bar', type: 'String' },
      addTypeProperty<Array<{z:string, v: boolean}>>({
        name: 'baz',
        type: 'JSON'
      })
    ];
    

    奇怪的是,typeOverride看起来像一个值,但最终我只需要将它用作类型 . 有没有办法以某种方式使用装饰器?

相关问题