You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在检查泛型键时抛出自定义TypeScript编译提示信息?

Customize TypeScript Error Message for Generic Key Filtering

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 08:38:01