简体   繁体   English

根据TypeScript中函数的行为自动生成/获取简单类型

[英]Automatically generate/get simple types based on behaviour of function in TypeScript

Given an object such as: 给定一个对象,例如:

const foo = {
   a: {id: 1},
   b: {id: 1},
   c: {id: 1},
   d: {id: 1},
   ....
}

and a function that converts the object to: 和一个将对象转换为的函数:

const bar = {
   a: 1,
   b: 1,
   c: 1,
   d: 1,
   ....
}

such as: 如:

function<MyInputInterface>(map: MyInputInterface): MyOutputInterface? {
  const newMap = {};
  _.forIn(map, (val, key) => {
      newMap[key] = val.id;
  }
  return newMap;
}

Is there a way to define only one interface in Typescript that automatically assumes the structure of the other (either input or output)? 有没有办法在Typescript中定义仅一个接口,该接口自动采用另一个接口的结构(输入或输出)? Eg passing MyInputInterface into the function will return MyOutputInterface ? 例如,将MyInputInterface传递给函数将返回MyOutputInterface

In general, the pattern I described is found in a lot of places in my code-base due to some library extracting meta information and returning only certain values (eg id).I could certainly define input/output as interfaces to get more type-information, but I'd be interested in seeing whether there is a solution to only have to define either input OR output and get the other type-info for free. 通常,由于某些库提取元信息并仅返回某些值(例如id),因此在代码库中的很多地方都可以找到我描述的模式。我当然可以将输入/输出定义为接口,以获取更多类型-信息,但我想看看是否有解决方案,只需定义输入或输出并免费获取其他类型信息即可。

Since this example might not be not clear enough, here a better example: 由于此示例可能还不够清楚,因此这里是一个更好的示例:

const properties = {
   propA: {
      desc: 'property a',
      val: 1
   },
   propB: {
      desc: 'property b',
      val: 'hello'
   }
   // any arbitrary number of properties
};

needs to convert to: 需要转换为:

const parsedProperties = {
  propA: 1,
  probB: 'hello'
};

you can try this: 您可以尝试以下方法:

private foo:Foo= {
    propA: {
        desc: 'property a',
        val: 1
    },
    propB: {
        desc: 'property b',
        val: 'hello'
    }
};

converter(foo:Foo , probName ):Bar{
    let bar:Bar={};
    for(let a in foo){
        bar[a] = foo[a][probName];
        }
    return bar;
    }
}

interface Foo{
    [propA: string]:{[propB:string]:string|number};
}
interface Bar{
    [name: string]:string|number ;
}

console.log('bar' , this.converter(this.foo , 'val' ));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM