TypeScript Any
The any type is a type that turns off type checking for a value. A value of type any can hold any kind of data and pass any check.
Any accepts every kind
An any variable can take a string, then a number, then a boolean. The typeof operator names the kind stored at each step.
let value: any = "hello";
console.log(typeof value);
value = 42;
console.log(typeof value);
value = true;
console.log(typeof value);Any flows into typed variables
An any value can move into a typed variable without a check. The stored value does not have to match the declared type.
let anything: any = "hello";
let count: number = anything;
console.log(count);A bad call fails at runtime
A method call on an any value passes the compiler without proof. The call fails while the program runs. instanceof asks whether a value was built by a named class.
let value: any = 42;
try {
value.shout();
} catch (err) {
if (err instanceof Error) {
console.log(err.message);
}
}Example
let data: any = "TypeScript";
console.log(data);
console.log(typeof data);
data = 2026;
console.log(data);
console.log(typeof data);
data = false;
console.log(data);
console.log(typeof data);Key points
- Any accepts a value of every type.
- Any can be assigned into a variable of any other type.
- Calls on an any value receive no check from the compiler.
- A wrong call on an any value fails while the program runs.
- The unknown type is the safer tool for a value whose kind is not yet known.
In this example, one any variable holds three kinds of value in turn. Each pair of logs shows the stored value and its runtime kind. No step raises an error, because any turns checking off.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What does the any type do to type checking?