gpt4 book ai didi

typescript 推断类型有时会解析为任何函数返回类型

转载 作者:搜寻专家 更新时间:2023-10-30 21:09:59 26 4
gpt4 key购买 nike

我试图描述围绕 JSON 映射函数的强类型安全约束。该函数将一个对象作为第一个参数,并使用作为第二个参数传递的映射函数返回该对象的映射表示。

从消费者的角度来看,像这样的契约(Contract):

let mappedResult = mapJson(
// Standard plain object literal coming, most of the time from serverside, generally described by an interface
// Let's call this type SRC
{ date: "2018-10-04T00:00:00+0200", date2: 1538604000000, aString: "Hello%20World", idempotentValue: "foo" },
// Applying some mapping aimed at converting input values above and change their type representation
// Rules are :
// - Keys should be a subset of SRC's keys, except for "new" computed keys
// - Values should be function taking SRC[key] and returning a new type NEW_TYPE[key] we want to capture in
// order to reference it in mapJson()'s result type
// Let's call this type TARGET_MAPPINGS
{ date: Date.parse, date2: (ts: number) => new Date(ts), aString: unescape, computed: (_, obj) => `${obj?`${obj.aString}__${obj.idempotentValue}`:''}` }
);
// Result type (NEW_TYPE) should be a map with its keys being the union of SRC keys and TARGET_MAPPINGS keys with following rules :
// - If key exists only in SRC, then NEW_TYPE[key] = SRC[key}
// - Otherwise (key existing in TARGET_MAPPINGS), then NEW_TYPE[key] = ResultType<TARGET_MAPPINGS[key]>
// In this example, expecting
// mappedResult = { date: Date.parse("2018-10-04T00:00:00+0200"), date2: new Date(1538604000000), aString: unescape("Hello%20World"), idempotentValue: "foo", computed: "Hello%20World__foo" }
// .. meaning that expected type would be { date: number, date2: Date, aString: string, idempotentValue: string, computed: string }

在一些帮助下(参见 this SO question)我设法让它主要用于以下类型:

type ExtractField<ATTR, T, FALLBACK> = ATTR extends keyof T ? T[ATTR] : FALLBACK;
type FunctionMap<SRC> = {
[ATTR in string]: (value: ExtractField<ATTR, SRC, never>, obj?: SRC) => any
}
type MappedReturnType<SRC, TARGET_MAPPINGS extends FunctionMap<SRC>> = {
[ATTR in (keyof TARGET_MAPPINGS | keyof SRC)]:
ATTR extends keyof TARGET_MAPPINGS ? ReturnType<Extract<TARGET_MAPPINGS[ATTR], Function>> : ExtractField<ATTR, SRC, never>
}

export function mapJson<
SRC extends object,
TARGET_MAPPINGS extends FunctionMap<SRC>
>(src: SRC, mappings: TARGET_MAPPINGS): MappedReturnType<SRC, TARGET_MAPPINGS> {
// impl .. not the point of the question
}

除了解析为类型 any 的“计算”属性情况外,一切看起来都不错(而不是 string )

let mappedResult = mapJson(
{ date: "2018-10-04T00:00:00+0200", date2: 1538604000000, aString: "Hello%20World", idempotentValue: "foo" },
{ date: Date.parse, date2: (ts: number) => new Date(ts), aString: unescape, computed: (_, obj) => `${obj?`${obj.aString}__${obj.idempotentValue}`:''}` }
);

let v1 = mappedResult.date; // number, expected
let v2 = mappedResult.date2; // Date, expected
let v3 = mappedResult.aString; // string, expected
let v4 = mappedResult.idempotentValue; // string, expected
let v5 = mappedResult.computed; // any, NOT expected (expectation was string here !)

我想这与 infer 有关类型解析,但我真的不明白为什么这适用于 SRC 中存在的属性& TARGET_MAPPINGS ( date , date2 & string ) 而不是仅存在于 TARGET_MAPPINGS 中的属性.

我可能发现了一个错误吗?

预先感谢您的帮助。

最佳答案

FunctionMap 根本没有按照您的意图进行。 TypeScript 不支持以 string 作为约束类型和不同属性类型的映射类型,具体取决于实际字符串。如果您尝试声明这样的映射类型,编译器会将其转换为具有字符串索引签名的类型,并仅将所有出现的键变量替换为 string ,即:

type FunctionMap<SRC> = {
[ATTR: string]: (value: ExtractField<string, SRC, never>, obj?: SRC) => any
}

现在,由于 string 不会为您正在使用的 keyof SRC 类型扩展 SRC,因此 value 参数的类型始终为 never 。然后,当评估 computedMappedReturnType<SRC, TARGET_MAPPINGS> 属性的类型时,ReturnType<Extract<TARGET_MAPPINGS[ATTR], Function>> 的评估失败,因为 Extract<TARGET_MAPPINGS[ATTR], Function>(value: never: obj?: SRC) => any ,并且 never(...args: any[]) => any 的约束 ReturnType 不兼容。 编译器通过将类型更改为 any 从失败中恢复;编译器不报错是个bug。 Issue 25673 具有相同的根本原因,因此我们应该将此案例添加到该问题而不是提交新的问题。 编辑:再想想,我认为这与问题 25673 和条件类型无关ReturnType 只是简化为其他情况,any

我试图为您的原始问题找到替代解决方案,但我无法让 TypeScript 在不将映射分成两个映射的情况下推断出正确的类型,一个用于原始属性,一个用于计算属性。即使不考虑上述问题,使用 never 作为计算属性的 value 参数的类型也是不合理的,因为您确实为该参数传递了一个值,大概是 undefined 。使用单个映射,我找不到让 TypeScript 推断 value 是原始属性的 SRC[ATTR] 和所有其他属性名称的 undefined 的方法。这是我想出的:

type FieldMap<SRC> = {
[ATTR in keyof SRC]?: (value: SRC[ATTR], obj: SRC) => any
};
type ComputedMap<SRC> = {
[ATTR in keyof SRC]?: never
} & {
[ATTR: string]: (value: undefined, obj: SRC) => any
};
type MappedReturnType<SRC, FM extends FieldMap<SRC>, CM extends ComputedMap<SRC>> = {
[ATTR in keyof CM]: ReturnType<CM[ATTR]>
} & {
[ATTR in keyof SRC]: ATTR extends keyof FM
? FM[ATTR] extends (value: SRC[ATTR], obj: SRC) => infer R ? R : SRC[ATTR]
: SRC[ATTR]
}

export function mapJson<
SRC extends object, FM extends FieldMap<SRC>, CM extends ComputedMap<SRC>
>(src: SRC, fieldMap: FM, computedMap: CM): MappedReturnType<SRC, FM, CM> {
// impl .. not the point of the question
return undefined!;
}

let mappedResult = mapJson(
{ date: "2018-10-04T00:00:00+0200", date2: 1538604000000, aString: "Hello%20World", idempotentValue: "foo" },
// Without `: number`, `ts` is inferred as any:
// probably https://github.com/Microsoft/TypeScript/issues/24694.
{ date: Date.parse, date2: (ts: number) => new Date(ts), aString: unescape},
{computed: (_, obj) => `${obj?`${obj.aString}__${obj.idempotentValue}`:''}` }
);

let v1 = mappedResult.date; // number, expected
let v2 = mappedResult.date2; // Date, expected
let v3 = mappedResult.aString; // string, expected
let v4 = mappedResult.idempotentValue; // string, expected
let v5 = mappedResult.computed; // string, expected

请注意,字段映射函数参数的上下文类型仍然不起作用。我认为这是由于 this TypeScript issue 造成的,我建议您对该问题投票。

关于 typescript 推断类型有时会解析为任何函数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52682862/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com