let foo = "bar"; // `foo` now holds the string value "bar"
Furthermore, just because a variable initially contained a string value doesn't mean that it can (from that point on) only contain string values. Values of different types can be freely assigned:
let foo = "bar"; // `foo` now holds the value "bar" of type string foo = false; // `foo` now holds the value false of type boolean foo = 1337; // `foo` now holds the value 1337 of type number
Built-In Types and the
symbol(added in ECMAScript 2015)
You can inquire about the type of a given value by using the
let foo = "bar"; typeof foo; // "string" foo = false; typeof foo; // "boolean" foo = 1337; typeof foo; // "number"
Although it might look like
typeof returns the type of the variable
The string returned by the
typeof operator is always one of these seven strings:
Notice that there's a (possibly surprising) mismatch between the seven built-in types and these seven strings, e.g.
typeof null === "object". The "Types and Grammar" book of the You Don't Know JS series by Kyle Simpson explains why this is.
Statically Typing Variables with TypeScript
let foo: string = "bar"; // `foo` now holds the value "bar" of type string foo = false; // Error: Type 'boolean' is not assignable to type 'string'