如何在检查泛型键时抛出自定义TypeScript编译提示信息?
Great question! The default error message from your current KeysOfTypeNumber<T> type is a bit vague, but we can absolutely tweak it to show a more user-friendly hint. Here's how to do it:
Solution Code
// Modified type with custom error hint type KeysOfTypeNumber<T> = { [Key in keyof T]: T[Key] extends number ? Key : `"${Key & string}" is not a key corresponding to a number type in the generic` }[keyof T]; type Keys = { currentPage: number prevPage: number searchParam: string } const passNumberKeys = <T>(numberTypeKeys: KeysOfTypeNumber<T>) => { console.log(numberTypeKeys) } passNumberKeys<Keys>('currentPage') // Still works fine passNumberKeys<Keys>('searchParam') // New error: Type '"searchParam"' is not assignable to type '"\"searchParam\" is not a key corresponding to a number type in the generic"'
How It Works
Your original type uses never for non-number keys, which gets "absorbed" into the union type of valid keys. This means TypeScript only tells you the value doesn't match KeysOfTypeNumber<Keys> without context.
By replacing never with a custom string literal type that includes the invalid key name and your hint, we make the error message explicit. When you pass an invalid key like 'searchParam', TypeScript will compare the string literal "searchParam" against the error literal we defined, and display the full hint in the error message.
Fine-Tuning the Message
If you prefer a more concise message (without the key name embedded), you can use a fixed literal instead:
type KeysOfTypeNumber<T> = { [Key in keyof T]: T[Key] extends number ? Key : 'Argument must be a key corresponding to a number type in the generic' }[keyof T];
This will give you the exact error message you originally wanted:
Type '"searchParam"' is not assignable to type '"Argument must be a key corresponding to a number type in the generic"'
Important Note
This approach doesn't break the valid case—when you pass a correct number key, TypeScript still recognizes it as a valid input since the error literal is only included in the union for non-number keys.
内容的提问来源于stack exchange,提问作者Arnas Savickas

