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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.