首页 > 解决方案 > 打字稿:与泛型的接口 - 在定义的对象内应用

问题描述

我有一个泛型接口:

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

问题:如何使用泛型声明一个接口,以便在特定情况下更具体地实例化属性类型?

标签: typescriptgenericstypesinterfaceproperties

解决方案


您需要定义有区别的联合:

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}`,
  }
];

操场

请看我的文章


推荐阅读