Basic · 3 of 13 · 11 min read
Primitive types
The lower-case types you should actually use, what strictNullChecks changes about all of them, and the object type you probably do not want.
- Primitives
JavaScript has seven primitives and TypeScript has a type for each. Nearly all the difficulty is in
two places: the capitalised wrapper types that look right and are not, and what strictNullChecks
does to every one of them.
The seven
let name: string = "Ana";
let age: number = 33; // one number type — no int/float distinction
let active: boolean = true;
let huge: bigint = 9007199254740993n;
let key: symbol = Symbol("id");
let nothing: null = null;
let missing: undefined = undefined;
number covers integers and floats alike, because JavaScript has one numeric type. bigint is
separate and deliberately does not mix with it:
const a: number = 1;
const b: bigint = 1n;
// console.log(a + b); // Operator '+' cannot be applied to 'number' and 'bigint'
console.log(a + Number(b), BigInt(a) + b); // 2 2n
Lower case, not upper case
| Write this | Not this | Why |
|---|---|---|
string |
String |
the primitive, not the wrapper object |
number |
Number |
same |
boolean |
Boolean |
same |
symbol |
Symbol |
same |
bigint |
BigInt |
same |
object |
Object |
Object accepts almost everything |
Assignability goes one way only, which is what makes the mistake bite:
let primitive: string = "hi";
let wrapper: String = primitive; // allowed
// let back: string = wrapper; // 'String' is not assignable to 'string'
function shout(text: string) { return text.toUpperCase(); }
// shout(wrapper); // the same error
console.log(shout(primitive)); // "HI"
So a single String annotation somewhere spreads errors through everything that touches it. The
capitalised types exist because the wrapper objects exist; you almost never want them.
strictNullChecks
Before this flag, null and undefined were assignable to every type, which made the type system
unable to warn about the most common runtime error there is. With it on they are ordinary types you
have to include deliberately.
let name: string = "Ana";
// name = null; // 'null' is not assignable to 'string'
let maybe: string | null = "Ana";
maybe = null; // fine
// console.log(maybe.length); // 'maybe' is possibly 'null'
console.log(maybe?.length ?? 0); // 0
The compiler then forces the check wherever the value is used, which is the entire point:
function describe(value: string | null | undefined): string {
if (value == null) return "nothing"; // catches both, idiomatically
return value.toUpperCase(); // narrowed to string
}
console.log(describe(null), describe("ok")); // "nothing" "OK"
Two related flags worth knowing: strictNullChecks is part of strict, and
noUncheckedIndexedAccess extends the same honesty to array and dictionary access, which is not
in strict and has to be opted into.
// with noUncheckedIndexedAccess
const items: string[] = [];
const first = items[0]; // string | undefined
console.log(first?.toUpperCase() ?? "empty");
null versus undefined
TypeScript keeps them distinct, and a codebase is calmer if it picks one meaning for each:
interface User {
name: string;
nickname?: string; // may be absent — undefined
deletedAt: Date | null; // present, deliberately empty — null
}
const user: User = { name: "Ana", deletedAt: null };
console.log(user.nickname ?? "none"); // "none"
console.log(user.deletedAt === null); // true
A convention that works: undefined for “was never set”, null for “set to nothing on purpose”.
APIs that send null for absent values are the usual reason defaults stop working, because a
default only fires for undefined.
const { nickname = "anon" } = { nickname: null as string | null };
console.log(nickname); // null — the default did not fire
object, {} and Object
Three types that look like they mean the same thing:
let a: object = [1, 2]; // any non-primitive — arrays and functions qualify
// let b: object = 42; // 'number' is not assignable to 'object'
let c: {} = 42; // fine! {} means "anything except null and undefined"
let d: Object = "hello"; // also fine — Object is even wider
// And none of them let you read anything:
// console.log(a.length); // Property 'length' does not exist on type 'object'
console.log(Object.keys(a).length); // 2
| Type | Accepts | Lets you read |
|---|---|---|
object |
anything non-primitive | nothing |
{} |
anything but null / undefined |
nothing |
Object |
the same as {}, plus the prototype members |
toString and friends |
Record<string, unknown> |
an object with unknown keys | values, as unknown |
| a declared shape | exactly that shape | its properties |
The usable choices are the bottom two. Record<string, unknown> says “a dictionary I will have to
check”; a declared interface says what you actually expect.
function keys(value: Record<string, unknown>) {
return Object.keys(value);
}
console.log(keys({ a: 1, b: 2 })); // ["a", "b"]
Literal types are primitives too
A single value can be a type, which is what makes unions of literals work:
let exact: "GET" = "GET";
// exact = "POST"; // not assignable
type Method = "GET" | "POST";
type Bit = 0 | 1;
type Truthy = true;
const m: Method = "POST";
const b: Bit = 1;
console.log(m, b);
Common mistakes
Using the capitalised types
Mistake. function greet(name: String).
Why it fails. String is the wrapper object type. A plain string goes in, but the value cannot
then be passed anywhere expecting string, so the error spreads outwards from the annotation.
What to do instead. Lower case, always.
Treating undefined and null as interchangeable
Mistake. A function that returns null for “missing”, used with ?? defaults and optional
properties that expect undefined.
Why it fails. Defaults in destructuring and default parameters fire only for undefined, so a
null passes straight through as a value.
What to do instead. Pick a convention, normalise at the boundary, and use ?? or == null
when you genuinely mean either.
Reaching for object when you mean a record
Mistake. function merge(target: object, source: object).
Why it fails. It accepts arrays, functions and dates, and lets you read nothing — so the body
needs casts, which is the opposite of what the annotation was for.
What to do instead. Record<string, unknown> for a dictionary, or the shape you actually need.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
Why is String the wrong annotation for a piece of text?
With strictNullChecks on, what does let name: string allow?
What does the object type mean in TypeScript?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.