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

如何在TypeScript中测试/断言变量类型不为any?

How to Check/Assert a Variable Isn't any in TypeScript (Compiler-Only, Single-Use)

Got it, I’ve got a perfect solution that fits all your requirements. We can use TypeScript’s conditional types to create a helper function that only throws a compiler error when you pass an any type—no runtime code needed, and it won’t affect your entire project (no need for --noImplicitAny or similar flags).

Here’s the implementation:

// Define a conditional type that rejects `any`
type NotAny<T> = T extends any 
  ? (any extends T ? never : T) 
  : T;

// Helper function that uses the type
function notAny<T>(x: NotAny<T>): void {}

How it works:

  • The NotAny<T> type leverages TypeScript’s quirky but useful compatibility rules for any: if T is any, then any extends T will evaluate to true (since any is compatible with every type, including itself). In that case, we return never—a type no value can be assigned to.
  • When you pass an any variable to notAny, the compiler detects you’re trying to assign any to a parameter expecting never, which triggers an error exactly where you want it.

Test it with your example scenario:

let foo: any = 'value';
notAny(foo); // ❌ Compiler error: Type 'any' is not assignable to type 'never'

let bar: string = 'hello';
notAny(bar); // ✅ No error at all—works fine for non-any types

Bonus: Friendlier error messages

If you want the error message to be more explicit, tweak the conditional type to return a string literal instead of never:

type AssertNotAny<T> = T extends any 
  ? (any extends T ? "❌ Invalid: Cannot pass an 'any' type here" : T) 
  : T;

function notAny<T>(x: AssertNotAny<T>): void {}

Now when you pass any, the error will read: Type 'any' is not assignable to type '"❌ Invalid: Cannot pass an 'any' type here"'—much clearer about what’s wrong.

This solution is totally single-use: you only get the check when you call notAny, and it doesn’t require any project-wide configuration changes. The function itself doesn’t need any runtime implementation (you can leave it empty) because we only care about the type checking.

内容的提问来源于stack exchange,提问作者SystematicFrank

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:29:21