我已经看到了一些相关的问题和GitHub的问题,但我仍然会询问具体的场景,以防不完全相同.
如果我们将对象文字obj
定义为
const obj = {
num1: 1,
num2: 2,
} as const;
当前可以创建和键入一个函数,该函数将对象值映射到另一种类型的值,而忽略来自条目/条目的对象周围的问题.等.
const mapObj = <T extends Record<string, unknown>, R>(
obj: T,
mapFn: (v: T[keyof T]) => R
): { [K in keyof T]: R } => ({} as any);
调用该函数会产生非常好的结果.
const mapped = mapObj(obj, (v) => `${v}`);
const mappedConst = mapObj(obj, (v) => `${v}` as const);
退货
{
readonly num1: string;
readonly num2: string;
}
和
{
readonly num1: "1" | "2";
readonly num2: "1" | "2";
}
分别取决于传递的函数.
I'd like to know if there is some approach that can allow the exact value types to be returned. key num1
should be "1"
和 num2
"2"
.
const mapObjExact = <T extends Record<string, unknown>, F extends <K extends keyof T>(k:K, v: T[K]) => unknown>(
obj: T,
mapFn: F
): { [K in keyof T]: ReturnType<F> } => ({} as any);
我不认为有任何方法可以为ReturnType
提供额外的信息,关于它将被用哪种类型的参数调用,所以我认为这种方法不起作用.但也许有一种不同的方法来构建函数.
I thought this may something to do with higher kinded types etc ... On the other h和 something like this for single value works.
const apply=<const T extends unknown,const R>(v:T,fn:(v:T)=>R):R=>fn(v)
const v1 = apply(2,(n)=>`${n}`) //"2"
但这是直接基于一个参数的,因此TypeScrip更容易猜测以确定类型.
我想这可能是不可能的,但我想知道是否有任何较新的类型脚本功能,如const泛型断言,或其他方法,是否有可能使其工作.