简体   繁体   English

Typescript-如何获取 object 上某个键的类型?

[英]Typescript- how to get the type of certain key on object?

const map ={
  a:1,
  b:'Hello world',
  c:()=>99,
  d:()=>'Love',
  e:()=>'adoration'
}

type LoveFunctionNameInString = keyof typeof map & ?

const result: LoveFunctionNameInString = 'd' | 'e'

I would like a type that points to the methods of string return type in 'map' object, so whenever I assign the type 'LoveFunctionNameInString' to a variable, Typescript would suggest me only 'd' |我想要一个指向 'map' object 中字符串返回类型方法的类型,所以每当我将类型 'LoveFunctionNameInString' 分配给变量时,Typescript 只会建议我 'd' | 'e' (because they are function of string return type) without 'a' | 'e'(因为它们是 function 的字符串返回类型)没有 'a' | 'b' | 'b' | 'c'. 'C'。

Inspired by this answer受此答案启发
Here's your working code -这是你的工作代码 -

const map ={
  a:1,
  b:'Hello world',
  c:()=>99,
  d:()=>'Love',
  e:()=>'adoration'
}

type KeysMatching<T, V> = NonNullable<
  { [K in keyof T]: T[K] extends V ? K : never }[keyof T]
>;

type LoveFunctionNameInString = KeysMatching<typeof map, () => string>;

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM