简体   繁体   English

如何从object中提取值类型和typescript中的键

[英]How to extract value type from object and keys in typescript

I am using arg and fp-ts .我正在使用argfp-ts I want to have a function that returns type based on one of the inputs key value.我想要一个 function 返回基于其中一个输入键值的类型。

export const getArg =  <T extends Spec> (args: Result<T>) => (argName: {[K in keyof T]: T[K]}): O.Option<T[K]> =>
    O.fromNullable(args[argName])

But it says that I can't index with K in keyof T , despite K being the actual keys.但它说我不能K in keyof T索引,尽管K是实际的键。 And it won't see K in Option .它不会在Option中看到K I need some help with types.我需要一些类型方面的帮助。

Result

    export type Result<T extends Spec> = { _: string[] } & {
        [K in keyof T]?: T[K] extends Handler
            ? ReturnType<T[K]>
            : T[K] extends [Handler]
            ? Array<ReturnType<T[K][0]>>
            : never;
    };

I couldn't make it work with arg library.我无法让它与arg库一起使用。 But I was able to extract type with command-line-args但我能够使用command-line-args提取类型

export const getArg =
  (args: CommandLineOptions) =>
  <K extends keyof CommandLineOptions>(
    argName: K
  ): O.Option<CommandLineOptions[K]> =>
    O.fromNullable(args[argName])

The right way to it was to use extends keyof instead of in keyof , and then reference the desired type via F[K]正确的方法是使用extends keyof而不是in keyof ,然后通过F[K]引用所需的类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 TypeScript 中的对象中提取所有键 - How to Extract All the keys from an Object in TypeScript Typescript:如何提取 const object 的值类型并将它们用作新类型中的键? - Typescript: How to extract the value types of a const object and use them as keys in a new type? 如何从对象中提取某种类型的键 - How to extract keys of certain type from object 如何从 typescript 中的 object 键生成 object 类型? - How to make object type from an object keys in typescript? 如何使 Typescript 推断 object 的键但定义其值的类型? - How to make Typescript infer the keys of an object but define type of its value? 从 Typescript 中的对象数组的属性中提取一个 key/value object 类型 - Extract a key/value object type from the properties of an array of objects in Typescript 如何在不知道键的情况下提取对象每个值的返回类型 - How to extract the return type of each value of an object without knowing the keys Typescript - 如何使用动态对象数组中的键动态键入对象 - Typescript - How to dynamically type an object with keys from a dynamic array of objects 如何从打字稿中的对象键字符串中提取确切的联合类型? - How to extract exact union type from object key strings in typescript? TypeScript 定义 object 密钥来自哪里? - TypeScript define object where keys will be from Type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM