首先,您需要从translations 中提取允许的值。为此,您需要使 translations 不可变。
const translations = {
msg_hello: 'Hello',
msg_bye: 'Bye'
} as const;
然后,为了可读性,你可以创建辅助类型:
type Translations = typeof translations;
感谢template literals,您可以推断出下划线_之后的字符串:
type GetSuffix<T> = keyof T extends `msg_${infer Suffix}` ? Suffix : never;
type Test = GetSuffix<Translations> // "hello" | "bye"
现在,您可以应用限制了:
const generateTranslation = <
Key extends GetSuffix<Translations>
>(partialKey: Key): `msg_${Key}` => `msg_${partialKey}`
请注意,我在 GetSuffix<Translations> 的帮助下推断出 partialKey,这有助于我应用显式返回类型 msg_${Key}。
整个例子:
const translations = {
msg_hello: 'Hello',
msg_bye: 'Bye'
} as const;
type Translations = typeof translations;
type GetSuffix<T> = keyof T extends `msg_${infer Suffix}` ? Suffix : never
type Test = GetSuffix<Translations> // "hello" | "bye"
const generateTranslation = <
Key extends GetSuffix<Translations>
>(partialKey: Key): `msg_${Key}` => `msg_${partialKey}`
const result = generateTranslation('hello'); // good ---> "msg_hello"
generateTranslation('no'); // bad
Playground