[英]How to define af function that pick nested property without loosing type in Typescript
i am looking for a way to select a nested property in a object of objects without loosing the type information of the given property using Typescript.我正在寻找一种方法来选择对象对象中的嵌套属性,而不会使用 Typescript 丢失给定属性的类型信息。
This could be the input for the function:这可能是函数的输入:
var fields = {email: {$: 'test'}, password: {$: 1}};
I would like to have a function that transforms this fields object into我想要一个函数来将这个字段对象转换成
var result = {email: 'test', password: 1}
Without loosing the type information on each fields.不会丢失每个字段的类型信息。 The email stays a string and password stays a number.
电子邮件保持字符串,密码保持数字。
The real use case is to pick the value field out of some form data object in order serilize it into JSON.真正的用例是从某个表单数据对象中挑选值字段,以便将其序列化为 JSON。
You can do this in Typescript 2.8 (unreleased at the time of writing, will be released in March 2018).您可以在 Typescript 2.8 中执行此操作(在撰写本文时尚未发布,将于 2018 年 3 月发布)。 This involves using conditional types and their associated inference behavior:
这涉及使用条件类型及其相关的推理行为:
type Unpacked<T> =
T extends { $: infer U } ? U : // if T has $ then we extarct the type of $
T;
var fields = {email: {$: 'test'}, password: {$: 1}};
function unpack<T>(obj: T) : { [P in keyof T] : Unpacked<T[P]>} {
return <any>null; // dummy implementation
}
var r = unpack(fields) // Will be typed as { email: string, password: number }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.