代码之家  ›  专栏  ›  技术社区  ›  Alexander Mills

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

  •  0
  • Alexander Mills  · 技术社区  · 7 年前

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

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

    很简单,但是如果要添加类型属性:

    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 回复  |  直到 7 年前
        1
  •  0
  •   Alexander Mills    7 年前

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

    '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看起来像一个值,但最终我只需要使用它作为类型。有没有办法用装修工来做这个?

    推荐文章