- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我试图描述围绕 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
。然后,当评估 computed
的 MappedReturnType<SRC, TARGET_MAPPINGS>
属性的类型时,ReturnType<Extract<TARGET_MAPPINGS[ATTR], Function>>
的评估失败,因为 Extract<TARGET_MAPPINGS[ATTR], Function>
是 (value: never: obj?: SRC) => any
,并且 never
与 (...args: any[]) => any
的约束 ReturnType
不兼容。 编译器通过将类型更改为 编辑:再想想,我认为这与问题 25673 和条件类型无关any
从失败中恢复;编译器不报错是个bug。 Issue 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/
我正在尝试编写一个相当多态的库。我遇到了一种更容易表现出来却很难说出来的情况。它看起来有点像这样: {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE
谁能解释一下这个表达式是如何工作的? type = type || 'any'; 这是否意味着如果类型未定义则使用“任意”? 最佳答案 如果 type 为“falsy”(即 false,或 undef
我有一个界面,在IAnimal.fs中, namespace Kingdom type IAnimal = abstract member Eat : Food -> unit 以及另一个成功
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: What is the difference between (type)value and type(va
在 C# 中,default(Nullable) 之间有区别吗? (或 default(long?) )和 default(long) ? Long只是一个例子,它可以是任何其他struct类型。 最
假设我有一个案例类: case class Foo(num: Int, str: String, bool: Boolean) 现在我还有一个简单的包装器: sealed trait Wrapper[
这个问题在这里已经有了答案: Create C# delegate type with ref parameter at runtime (1 个回答) 关闭 2 年前。 为了即时创建委托(dele
我正在尝试获取图像的 dct。一开始我遇到了错误 The function/feature is not implemented (Odd-size DCT's are not implemented
我正在尝试使用 AFNetworking 的 AFPropertyListRequestOperation,但是当我尝试下载它时,出现错误 预期的内容类型{( “应用程序/x-plist” )}, 得
我在下面收到错误。我知道这段代码的意思,但我不知道界面应该是什么样子: Element implicitly has an 'any' type because index expression is
我尝试将 SignalType 从 ReactiveCocoa 扩展为自定义 ErrorType,代码如下所示 enum MyError: ErrorType { // .. cases }
我无法在任何其他问题中找到答案。假设我有一个抽象父类(super class) Abstract0,它有两个子类 Concrete1 和 Concrete1。我希望能够在 Abstract0 中定义类
我想知道为什么这个索引没有用在 RANGE 类型中,而是用在 INDEX 中: 索引: CREATE INDEX myindex ON orders(order_date); 查询: EXPLAIN
我正在使用 RxJava,现在我尝试通过提供 lambda 来订阅可观察对象: observableProvider.stringForKey(CURRENT_DELETED_ID) .sub
我已经尝试了几乎所有解决问题的方法,其中包括。为 提供类型使用app.use(express.static('public'))还有更多,但我似乎无法为此找到解决方案。 index.js : imp
以下哪个 CSS 选择器更快? input[type="submit"] { /* styles */ } 或 [type="submit"] { /* styles */ } 只是好
我不知道这个设置有什么问题,我在 IDEA 中获得了所有注释(@Controller、@Repository、@Service),它在行号左侧显示 bean,然后转到该 bean。 这是错误: 14-
我听从了建议 registering java function as a callback in C function并且可以使用“简单”类型(例如整数和字符串)进行回调,例如: jstring j
有一些 java 类,加载到 Oracle 数据库(版本 11g)和 pl/sql 函数包装器: create or replace function getDataFromJava( in_uLis
我已经从 David Walsh 的 css 动画回调中获取代码并将其修改为 TypeScript。但是,我收到一个错误,我不知道为什么: interface IBrowserPrefix { [
我是一名优秀的程序员,十分优秀!