【问题标题】:Typescript generic that extends the `keyof` a dictionary with keys constrained to `string` is not constrained to `string`扩展 `keyof` 的 Typescript 泛型,一个键被限制为 `string` 的字典不受限于 `string`
【发布时间】:2022-11-30 08:53:22
【问题描述】:

如果我有一个字典 D,其中的键被限制为键入 string,则类型为 keyof D 的泛型似乎仍被推断为 string | number | symbol

一个基本的 ts 游乐场示例here

type Foo = {
  [key: string]: any
}

const bar = (blah: string) => {
  return blah;
}

const foo = <T extends Foo, N extends keyof T>(dict: T, key: N) => {
  bar(key); // Err: Type 'number' is not assignable to type 'string'.
  console.log(dict);
}

在上面的示例中,我如何约束 N 以便它:

  • 可以传入bar
  • 一定是字典T的键之一?

【问题讨论】:

    标签: typescript generics


    【解决方案1】:

    问题是:

    const sym = Symbol('mysym')
    const test = { abc: 123, [sym]: 456 }
    const foo: Foo = test // fine
    

    所以类型:

    { abc: number, [sym]: number }
    

    实际上扩展了类型:

    { [key: string]: any }
    

    如果您希望将 N 限制为仅字符串,那么您可以将该要求与 N 的约束相交。

    const foo = <
      T extends Foo,
      N extends keyof T & string
    >(dict: T, key: N) => {
      return bar(key);
    }
    
    foo({ a: 123 }, 'a') // fine
    foo({ a: 123 }, 'b') // error
    

    See Playground

    【讨论】:

    • 完美的。谢谢!
    猜你喜欢
    • 2020-08-20
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 2017-04-17
    • 2021-09-29
    • 1970-01-01
    相关资源
    最近更新 更多