【发布时间】: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