0

Say we have an array like so:

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

simple enough, but what if we want to add a type property:

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
 }
];

but of course that doesn't work, we can't use a type as a value like that - what I am wondering is if there is a way to add a type property to an array element somehow.

Something like this:

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' 
 })
];

anyone know what I am talking about? Maybe I can use a decorator?

The addTypeProperty needs to add typeOverride property to the argument somehow.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

0

I think this is right, but not quite sure:

'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'
  })
];

the weird thing is that typeOverride appears like a value, but ultimately I just need to use it as type. Is there a way to use a decorator for this somehow?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817