typescript - 打字稿:与泛型的接口 - 在定义的对象内应用
问题描述
我有一个泛型接口:
interface InterfaceWithGenerics<
Dict extends Record<string, any>,
Key extends keyof Dict = keyof Dict
> {
key: Key;
dictValueFormatter: ((key: Key, value: Dict[Key]) => any);
}
当我定义实现此接口的对象时,我希望将泛型应用于对象属性并实例化它们的类型。例如:
interface SomeDictionary {
foo: string;
bar: number;
baz: boolean;
}
export const dictConfig: InterfaceWithGenerics<SomeDictionary>[] = [
{
key: 'foo',
dictValueFormatter: (key, value) => `${key}:${value}`,
}
];
但它不会发生。VS Code 使用 prop (Fact)dictValueFormatter
为内部对象显示以下类型:key='foo'
(key: keyof SomeDictionary, value: string | number | boolean) => any
预期:
(key: 'foo', value: string) => any
问题:如何使用泛型声明一个接口,以便在特定情况下更具体地实例化属性类型?
解决方案
您需要定义有区别的联合:
type InterfaceWithGenerics<
Dict extends Record<string, any>,
> = {
[Key in keyof Dict]: {
key: Key;
dictValueFormatter: ((key: Key, value: Dict[Key]) => any);
}
}
type Values<T> = T[keyof T]
interface SomeDictionary {
foo: string;
bar: number;
baz: boolean;
}
export const dictConfig: Values<InterfaceWithGenerics<SomeDictionary>>[] = [
{
key: 'foo',
dictValueFormatter: (key, value) => `${key}:${value}`,
}
];
请看我的文章
推荐阅读
- python - 使用 plt.plot 绘制图表时遇到问题
- laravel - Laravel 日志文件权限问题
- wordpress - 如何仅重写 Wordpress 主页 url?
- python - 模板文件中的静态块标签无效
- jquery - 根据下拉选择值显示/隐藏元素
- java - 我们应该在 java 测试文件夹还是主文件夹中编写 testng selenium 代码?
- spring-boot - 使用 Facebook 登录:错误请求。主机和端口的这种组合需要 TLS
- django - 如何使用 kwargs 正确初始化类实例
- angularfire2 - 如何组合成角度的防火板?
- python - “Figure”对象没有“show”属性