【问题标题】:TypeScript narrow down the keys of indexable type by its value typesTypeScript 通过其值类型缩小可索引类型的键
【发布时间】:2019-08-10 15:05:31
【问题描述】:

鉴于我们有一个通用的可索引类型,我怎样才能只检索其值的类型以便能够缩小到只有一些键?

// imagine check is a function and its second argument only allows the property `a` as it's string and raise an error if 'b' is passed
const test2 = check({ a: 'string', b: 22 }, 'b'); // error only 'a' is allowed
const test2 = check({ a: 'str', b: 'str2' }, 'b'); // ok returns 'str2'

【问题讨论】:

    标签: typescript


    【解决方案1】:

    当然,您可以通过使用conditionalmapped 类型来仅提取对象类型T 的键,其值与值类型V 匹配:

    type KeysMatching<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];
    declare function check<T>(obj: T, k: KeysMatching<T, string>): string;
    
    const test1 = check({ a: 'string', b: 22 }, 'b'); // error 
    const test2 = check({ a: 'str', b: 'str2' }, 'b'); // ok 
    

    希望对您有所帮助。祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 2021-10-25
      • 2017-06-11
      • 2020-07-22
      • 1970-01-01
      • 2020-03-11
      • 2020-07-21
      相关资源
      最近更新 更多