简体   繁体   English

是否有可能(还)返回一个输入对象,其输入类型按属性映射?

[英]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.

相关问题 使用映射类型返回函数返回类型的对象 - Using mapped types to return object of return types of functions 是否可以在 typescript 的映射类型中推断函数的返回类型? - Is it possible to infer return type of functions in mapped types in typescript? TypeScript:在映射对象中推断特定类型的参数和函数的返回值 - TypeScript: Infer specific types of arguments and return values of functions in a mapped object Typescript中的映射对象类型 - Mapped object types in Typescript 是否可以为 httpsCallable 函数指定输入和返回类型? - Is it possible to specify input and return types for httpsCallable functions? 打字稿中的映射函数类型可能吗? - Possible for mapped function types in typescript? 为所有可能的对象属性类型定义一个类型 - Define a type for all possible object property types 通过 object 属性推断条件返回泛型类型 - Infer conditional return generic types by object property 打字稿泛型:返回数组类型以按位置与映射类型匹配输入数组 - Typescript generics: Return array type to match input array by position with mapped types 映射类型:根据同一个 object 的数组是否包含字符串字面量,使属性成为必需 - Mapped types: Make property required based on whether array of same object contains string literal
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM