[英]How to extract value type from object and keys in typescript
I am using arg
and fp-ts
.我正在使用
arg
和fp-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.