Basic Types
Primitives
TypeScript's basic types correspond to JavaScript's primitives:
let message: string = "Hello, world";
let someValue: number = 42;
let isAwesome: boolean = true;
let big: bigint = 100n;
let id: symbol = Symbol("id");
let nothing: null = null;
let notSet: undefined = undefined;
string, number, boolean). The uppercase String, Number and Boolean are wrapper objects and almost never what you want.Type Inference
You can omit type annotations, TypeScript tries to automatically infer the types:
let message = "Hello, world"; // inferred as string
message = 42; // Error: Type 'number' is not assignable to type 'string'
Annotate when TypeScript can't infer a useful type (function parameters, empty variables) and let it infer everything else.
any
TypeScript also has a special type, any, that you can use whenever you don’t want a particular value to cause typechecking errors.
let obj: any = { x: 0 };
// None of the following lines of code will throw compiler errors.
// Using `any` disables all further type checking and it is assumed
// you know the environment better than TypeScript.
obj.foo();
obj.bar = 100;
obj = "hello";
const n: string = obj;
When you don’t specify a type and TypeScript can’t infer it from context (common in function parameters), the compiler will typically default to any. The noImplicitAny flag turns this into an error; it's part of strict, which is on by default since TypeScript 6.0.
unknown
unknown is the safe version of any: it accepts any value, but you can't use the value until you check what it is.
let input: unknown = JSON.parse('"hello"');
input.toUpperCase(); // Error: 'input' is of type 'unknown'
if (typeof input === "string") {
input.toUpperCase(); // OK: TypeScript now knows it's a string
}
Prefer unknown over any for values whose type you don't know yet (API responses, JSON.parse, catch errors).
void and never
| Type | Meaning |
|---|---|
void | A function returns nothing useful (see Functions). |
never | A value that can never exist, e.g. a function that always throws. |
function fail(message: string): never {
throw new Error(message);
}
Type Assertion
In TypeScript, Type Assertion is a way to override TypeScript’s type inference, without changing the runtime behavior.
let value: unknown = "hello";
// `as` syntax (preferred, especially in React/JSX)
let length = (value as string).length;
// Angle Bracket syntax (not allowed in .tsx files)
let length2 = (<string>value).length;
string, the code still compiles and fails at runtime. Prefer narrowing with typeof (see Union & Literal Types).