Select 单个 属性 通用 TypeScript 接口作为方法参数中的变量传入

Select single property of generic TypeScript interface to pass in as variable in method argument

我在定义一个只允许将 TypeScript 接口的 1 属性 作为参数传递给方法的方法时遇到了一些困难。

getTranslation<T, TProperty>(activeLocale: Locale, translations: MobilityTranslations<T>, property: TProperty): string

我想要实现的是 property 参数是接口 T 的单个 属性。

有没有办法在 TypeScript 中实现这个?

interface TranslationKeys {
  translation1: string
  translation2: string
}

// Returns the string value for property translation1
getTranslation(activeLocale, translations, 'translation1')

// Typescript error because translation3 is no property on interface TranslationKeys
getTranslation(activeLocale, translations, 'translation3')

解决方案:

我正在寻找的 typescript 关键字是 keyof T,因为已经提到了解决我问题的可爱的人。

谢谢大家!

这应该是您要查找的内容:

getTranslation<T>(activeLocale: Locale, translations: MobilityTranslations<T>, property: keyof T): string

当您传入 translations 参数时,TypeScript 将从 MobilityTranslations<T> 泛型推断 T 并将 property 参数限制为仅 [=13] 的键=].

您还可以将 T 泛型参数限制为一个对象,以便签名更加明确:

getTranslation<T extends object>(activeLocale: Locale, translations: MobilityTranslations<T>, property: keyof T): string

这会防止有人写 MobilityTranslations<number>,例如,这会给您可能不需要的字符串文字。