【问题标题】:How to verify that indexed type extends string?如何验证索引类型是否扩展了字符串?
【发布时间】:2022-12-14 17:29:29
【问题描述】:

假设我有带有 2 个通用参数的函数 func

const func = <T extends {}, K extends keyof T>() => {};

和一个类型

interface Form {
  a: boolean;
  b: string;
}

然后我可以像这样调用它们而不会出现任何错误

func<Form, "a">();
func<Form, "b">();

现在我希望 func 只接受 T[K] = string 的键 换句话说

func<Form, "a">(); // should fail
func<Form, "b">(); // should pass

我的伪打字稿解决方案是

const func = <T extends {}, K extends keyof T : where T[K] extends string>() => {};

但这当然不会走得太远。有可能吗? 任何帮助表示赞赏。

【问题讨论】:

    标签: typescript generics extends keyof


    【解决方案1】:

    使用一个小助手类型来获取所有字符串类型的键:

    type StringKeys<T> = {
      [K in keyof T]:
        T[K] extends string ? K : never
    }[keyof T]
    
    type Test = StringKeys<{ a: boolean, b: string, c: string }>
    // type: 'b' | 'c'
    

    此实用程序类型映射 T 的所有属性,如果值类型扩展为字符串,则保留键名,否则将作为永不丢弃。

    然后你只需像这样使用它:

    interface Form {
      a: boolean;
      b: string;
    }
    
    const func = <T, K extends StringKeys<T>>() => {};
    
    func<Form, "a">(); // error
    func<Form, "b">(); // fine
    

    See Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-20
      • 1970-01-01
      • 2019-03-18
      • 2011-09-29
      • 2020-09-10
      • 2011-04-07
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多