[英]Is it possible (yet) to return an input object with its types mapped per property?
In short, I want a function which takes an non-predefined type like this: 简而言之,我想要一个采用非预定义类型的函数,如下所示:
{
name: string,
list: Array,
metadata: Object,
}
and returns this 并返回这个
{
name: MyStringProxy,
list: MyArrayProxy,
metadata: MyObjectProxy,
}
I know how to get an object returned where every property has the same type ( Object with the same keys as another object in typescript? )... 我知道如何在每个属性具有相同类型的情况下返回对象( 与打字稿中的另一个对象具有相同键的对象? )...
abstract function allPropsAre42<TYPE_IN>(obj: TYPE_IN): { [key in keyof TYPE_IN]: 42 };
...which is a good starting point, but it only maps everything to one type. ...这是一个很好的起点,但是它仅将所有内容映射到一种类型。 I want to map each type to another.
我想将每种类型映射到另一种。
I'm pretty sure it isn't possible, but here's some made up pseudo-code which would be like what I'm looking for: 我很确定这是不可能的,但是这里有一些伪代码,就像我要寻找的一样:
interface IPropMap {
string: MyStringProxy,
Array: MyListProxy,
Object: MyObjectProxy,
}
// not real code
abstract function mapAllProps<TYPE_IN>(obj: TYPE_IN): {
[key in keyof TYPE_IN]: IPropMap[TYPE_IN[key]]
};
Is it possible to do such a thing in typescript? 可以在打字稿中做这样的事情吗?
https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types
Figured it out. 弄清楚了。 Using conditional type mapping, this can be done:
使用条件类型映射,可以做到这一点:
type TypeName<T> =
T extends string ? MyStringProxy :
T extends Array ? MyArrayProxy :
T extends object ? MyObjectProxy :
undefined;
abstract function mapAllProps<TYPE_IN>(obj: TYPE_IN): {
[key in keyof TYPE_IN]: TypeName[TYPE_IN[key]]
};
My guess wasn't too far off. 我的猜测距离还不太远。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.