打字稿:与泛型的接口 - 在定义的对象内应用
Typescript: interface with generics - applying inside defined object
我有泛型接口:
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 显示 dictValueFormatter
内部对象的以下类型 key='foo'
(Fact):
(key: keyof SomeDictionary, value: string | number | boolean) => any
预期:
(key: 'foo', value: string) => any
问题:如何使用泛型声明一个接口,以便在特定情况下更具体地实例化属性类型?
你需要定义discriminated union:
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}`,
}
];
请看我的article
我有泛型接口:
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 显示 dictValueFormatter
内部对象的以下类型 key='foo'
(Fact):
(key: keyof SomeDictionary, value: string | number | boolean) => any
预期:
(key: 'foo', value: string) => any
问题:如何使用泛型声明一个接口,以便在特定情况下更具体地实例化属性类型?
你需要定义discriminated union:
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}`,
}
];
请看我的article