如何在TypeScript中测试/断言变量类型不为any?
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 forany: ifTisany, thenany extends Twill evaluate totrue(sinceanyis compatible with every type, including itself). In that case, we returnnever—a type no value can be assigned to. - When you pass an
anyvariable tonotAny, the compiler detects you’re trying to assignanyto a parameter expectingnever, 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

