简体   繁体   English

如何定义选择嵌套属性而不丢失 Typescript 中的类型的 af 函数

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

相关问题 Typescript 如何用嵌套和预测定义数组类型 - Typescript how to define array type with nested and predict 打字稿:类型“{}”不能指定为“选择”类型 <T, K> &#39;,如何正确输入javascript`pick`功能? - Typescript: Type '{}' is not assignable to type 'Pick<T, K>', how do I type javascript `pick` function correctly? 如何在 typescript 中键入定义 zip function - how to type define a zip function in typescript Typescript - 如何根据另一个属性有条件地定义类型 - Typescript - How can I conditionally define a type based on another property TypeScript-如何使用任何类型的参数定义函数类型 - TypeScript - How to define Function Type having arguments with any Type 如何在打字稿中定义计算属性 - how define computed property in typescript 是否可以在TypeScript中为属性名称定义类型 - Is it possible to define a type for property names in TypeScript Typescript:如何用布尔值或回调函数定义联合类型? - Typescript: how do you define a union type with boolean or a callback function? 如何在 React TypeScript 中定义一次类型并将其分配给函数和组件? - How to define a type once and assign it to a function and a component in React TypeScript? 如何根据Typescript中的字符串参数定义函数的参数类型? - How to define a function's argument type dependent on string argument in Typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM